Ch. 6 File I-O Handling and Exception Handling
Ch. 6 File I-O Handling and Exception Handling
Learning Objectives…
[
6.0 INTRODUCTION
• A file is a collection of related data that acts as a container of storage as data permanently. The file
processing refers to a process in which a program processes and accesses data stored in files.
• A file is a computer resource used for recording data in a computer storage device. The processing on
a file is performed using read/write operations performed by programs.
• Python supports file handling and allows users to handle files i.e., to read and write files, along with
many other file handling options, to operate on files.
• Python programming provides modules with functions that enable us to manipulate text files and
binary files. Python allows us to create files, update their contents and also delete files.
• A text file is a file that stores information in the term of a sequence of characters (textual
information), while a binary file stops stores data in the form of bits (0s and 1s) and used to store
information in the form as text, images, audios, videos etc.
6.1 I/O OPERATIONS (READING KEYBOARD INPUT AND PRINTING TO
SCREEN)
• In any programming language an interface plays a very important role. It takes data from the user
(input) and displays the output.
• One of the essential operations performed in Python language is to provide input values to the
program and output the data produced by the program to a standard output device (monitor).
[6.1]
Programming with 'Python' 6.2 File I/O Handling and Exception Handling
• The output generated is always dependent on the input values that have been provided to the
program. The input can be provided to the program statically and dynamically.
• In static input, the raw data does not change in every run of the program. While in dynamic input,
the raw data has a tendency to change in every run of the program.
• Python language has predefined functions for reading input and displaying output on the screen,
Input can also be provided directly in the program by assigning the values to the variables. Python
language provides numerous built in functions that are readily available to us at Python prompt.
• Some of the functions like input() and print() are widely used for standard Input and Output (I/O)
operations, respectively.
1. Output (Printing to Screen):
• The function print() is used to output data to the standard output devices i.e., monitor/screen. The
output can redirect or store on to a file also.
• The message can be a string, or any other object, the object will be converted into a string before
written to the screen.
Syntax: print(object(s), separator=separator, end=end, file=file, flush=flush)
Parameter Values:
(i) object(s): Any object, and as many as you like. Will be converted to string before printed.
(ii) sep='separator': Optional. Specify how to separate the objects, if there is more than one. Default
is ' '.
(iii)end='end': Optional. Specify what to print at the end. Default is '\n' (line feed).
(iv) file: Optional. An object with a write method. Default is sys.stdout.
(v) flush: Optional. A Boolean, specifying if the output is flushed (True) or buffered (False). Default
is False.
Example: For output using print().
>>> print("Hello", "how are you?", sep=" ---")
Hello ---how are you?
>>> print(10,20,30,sep='-')
10-20-30
• To make the output more attractive formatting is used. This can be done by using the str.format()
method.
Example: For output using format().
>>> a=10
>>> b=20
>>> print('Value of a is {} and b is {}'.format(a,b))
Value of a is 10 and b is 20
>>> print('I will visit {0} and {1} in summer'.format('Jammu','Kashmir')
I will visit Jammu and Kashmir in summer
>>>
• Alike old sprint() style used in C programming language, we can format the output in Python
language also. The % operator is used to accomplish this.
Example: For output with %.
>>> x=12.3456789
>>> print('The value of x=%3.2f'%x)
The value of x=12.35
>>> print('The value of x=%3.4f'%x)
The value of x=12.3457
• The various format symbols available in Python programming are:
Programming with 'Python' 6.3 File I/O Handling and Exception Handling
>>> x=float(input())
2.5
>>> type(x)
<class 'float'>
6.2 FILES
• File is a named location on disk to store related information. It is used to permanently store data in a
non-volatile memory (e.g. hard disk).
• Since, Random Access Memory (RAM) is volatile which loses its data when computer is turned OFF,
we use files for future use of the data.
• Files are divided into following two categories:
1. Text Files: Text files are simple texts in human readable format. A text file is structured as
sequence of lines of text.
2. BinaryFiles: Binary files have binary data which is understood by the computer.
• When we want to read from or write to a file we need to open it first. When we are done, it needs to
be closed, so that resources that are tied with the file are freed.
• Hence, in Python a file operation takes place in the following order:
o Open a file.
o Read or write (perform operation).
o Close the file.
6.2.1 Opening File in Different Modes
• All files in Python are required to be open be fore some operation (read or write) can be performed on
the file. In Python programming while opening a file, file object is created, and by using this file
object we can perform different set as operations on the opened file.
• Python has a built-in function open() to open a file. This function returns a file object also called a
handle, as it is used to read or modify the file accordingly.
Syntax: file object = open(file_name [, access_mode][, buffering])
Parameters:
file_name: The file_name argument is a string value that contains the name of the file that we want
to access.
access_mode: The access_mode determines the mode in which the file has to be opened, i.e., read,
write, append, etc. This is optional parameter and the default file access mode is read (r).
buffering: If the buffering value is set to 0, no buffering takes place. If the buffering value is 1, line
buffering is performed while accessing a file. If we specify the buffering value as an integer greater
than 1, then buffering action is performed with the indicated buffer size. If negative, the buffer size
is the system default (default behavior).
If the path is in current working directory, we can just provide the filename, just like in the following
examples:
>>> file=open("sample.txt")
>>> file.read()
'Hello I am there\n' # content of file
>>>
• If still we are getting “no such file or directory” error then use following command to confirm the
proper file name and extension:
>>> import os
>>> os.listdir()
['DLLs', 'Doc', 'etc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'mypkg', 'NEWS.txt',
'p1.py', 'p2.py', 'python.exe', 'python3.dll', 'python37.dll', 'pythonw.exe',
Programming with 'Python' 6.5 File I/O Handling and Exception Handling
• Closing a file will free up the resources that were tied with the file and is done using
Python close() method.
Syntax: fileObject.close()
Example: For closing a file.
f=open("sample.txt")
print("Name of the file: ",f.name)
f.close()
Output:
Name of the file: sample.txt
fruits=["Orange\n","Banana\n","Apple\n"]
f=open("sample.txt",mode="w+",encoding="utf-8")
f.writelines(fruits)
f.close()
f=open("sample.txt","r")
print(f.read())
Output:
Orange
Banana
Apple
>>>
third line
3. readlines(): This method maintains a list of each line in the file.
Example: For roadlines() method.
f=open("sample.txt","r")
print(f.readlines())
Output:
['first line\n', 'second line\n', 'third line\n']
37
0
first line
second line
third line
>>>
Example 2:
fruits=["Orange\n","Banana\n","Apple\n"]
f=open("sample.txt",mode="w+",encoding="utf-8")
for fru in fruits:
f.write(fru)
Programming with 'Python' 6.10 File I/O Handling and Exception Handling
• It has methods to view environment variables of the operating system on which Python is working
on and many more.
Sr. No. Method Function
1. os.getcwd() Show current working directory.
2. os.path.getsize() Show file size in bytes of file passed in parameter.
3. os.path.isfile() Is passed parameter a file.
4. os.path.isdir() Is passed parameter a folder.
5. os.chdir() Change directory/folder.
6. os.rename(current,new) Rename a file.
7. os.remove(file_name) Delete a file.
8. os.makedirs() Create a new folder.
Example: For handling files through OS module.
import os
os.getcwd()
print("***Contents of Present working directory***\n ", os.listdir())
print(os.path.isfile("sample.txt"))
print(os.path.isdir("sample.txt"))
>>> os.getcwd()
'C:\\Users\\ Meenakshi \\AppData\\Local\\Programs\\Python\\Python37-32'
os.rmdir("mydir1")
OSError: [WinError 145] The directory is not empty: 'mydir1'
>>>
os.chdir("C:\\Users\\Meenakshi\\AppData\\Local\\Programs\\Python\\Python37\mydir1")
>>> os.listdir()
['sample.txt']
>>> os.remove("sample.txt")
>>> os.listdir()
[]
>>> os.chdir("C:\\Users\\Meenakshi\\AppData\\Local\\Programs\\Python\\Python37")
>>> os.rmdir("mydir1")
>>>
• In order to remove a non-empty directory we can use the rmtree() method inside the shutil module.
>>> import shutil
>>> shutil.rmtree('test')
Sr.
Function Description Examples
No.
1. <file.close()> Close the file. We need to reopen it f.close()
for further access.
2. <file.flush()> Flush the internal buffer. It’s same as f.flush()
the <stdio>’s <fflush()> function. print(f.read())
f.close()
3. <file.fileno()> Returns an integer file descriptor. print(f.fileno())
f.close()
4. <file.isatty()> It returns true if file has a <tty> print(f.isatty())
attached to it. f.close()
5. <file.next()> Returns the next line from the last try:
offset. whilef.next():
print(f.next())
except:
f.close()
6. <file.read()> This function reads the entire file and lines =f.read()
returns a string. f.write(lines)
f.close()
7. <file.read(size)> Reads the given no. of bytes. It may text =f.read(10)
read less if EOF is hit. print(text)
f.close()
8. file.readline() Reads a single line and returns it as a text =f.readline()
string. print(text)
f.close()
9. <file.readline(size)> It’ll read an entire line (trailing with a text =f.readline(20)
Programming with 'Python' 6.15 File I/O Handling and Exception Handling
Sr.
No Function Description Examples
.
1. os.getcwd() Show current working import os
directory. os.getcwd()
2. os.path.getsize() Show file size in bytes of file size =os.path.getsize(“sample.txt”)
passed in parameter.
3. os.path.isfile() print(os.path.isfile("sample.txt"))
Is passed parameter a file.
7. os.rename(current,new) os.rename("sample.txt","sample1.txt
Rename a file.
")
8. os.remove(file_name) Delete a file. os.remove("sample.txt")
9. os.mkdir() Creates a single subdirectory. os.mkdir("testdir")
10. os.chdir(path) Change the current working os.chdir("d:\IT")
directory to path.
Additional Programs:
1. Program to create a simple file and write some content in it.
print("Enter 'x' for exit.");
filename = input("Enter file name to create and write content: ");
if filename == 'x':
exit();
else:
c = open(filename, "w");
print("\nThe file,",filename,"created successfully!");
print("Enter sentences to write on the file: ");
sent1 = input();
c.write(sent1);
c.close();
print("\nContent successfully placed inside the file.!!");
Output:
Enter 'x' for exit.
Enter file name to create and write content: file1
>>> if (a<5)
SyntaxError: invalid syntax
>>> 5/0
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
5/0
ZeroDivisionError: division by zero
6.3.1 Introduction
• An exception is also called ad runtime error that can halt the execution of the program.
• An exception is an error that happens/occurs during execution of a program. When that error
occurs, Python generate an exception that can be handled, which avoids the normal flow of the
program's instructions.
• Errors detected during execution are called exceptions. An exception is an event (usually an error),
which occurs during the execution of a program that disrupts the normal flow of execution as the
program.
• In Python programming we can handle exceptions using try-except statement, try-finally
statement and raise statement.
• Following table list all the standard exceptions available in Python programming language:
Sr. No. Exception Cause of Error
1. ArithmeticError Base class for all errors that occur for numeric calculation.
2. AssertionError Raised in case of failure of the assert statement.
3. AttributeError Raised in case of failure of attribute reference or
assignment.
4. Exception Base class for all exceptions.
5. EOFError Raised when there is no input from either the raw_input()
or input() function and the end of file is reached.
6. EnvironmentError Base class for all exceptions that occur outside the Python
environment.
7. FloatingPointError Raised when a floating point calculation fails.
8. ImportError Raised when an import statement fails.
9. IndexError Raised when an index is not found in a sequence.
10. IOError Raised when an input/ output operation fails, such as the
print statement or the open() function when trying to open
a file that does not exist.
11. IndentationError Raised when indentation is not specified properly.
12. KeyboardInterrupt Raised when the user interrupts program execution,
usually by pressing Ctrl+c.
13. KeyError Raised when the specified key is not found in the
dictionary.
14. LookupError Base class for all lookup errors.
15. NameError Raised when an identifier is not found in the local or global
namespace.
16. NotImplementedError Raised when an abstract method that needs to be
implemented in an inherited class is not actually
implemented.
Programming with 'Python' 6.19 File I/O Handling and Exception Handling
• The associated except blocks are used to handle any resulting exceptions thrown in the try block.That
is we want the try block to succeed and if it does not succeed, we want to control to pass to the catch
block.
• If any statement within the try block throws an exception, control immediately shifts to the catch
block. If no exception is thrown in the try block, the catch block is skipped.
• There can be one or more except blocks. Multiple except blocks with different exception names can
be chained together.
• The except blocks are evaluated from top to bottom in the code, but only one except block is executed
for each exception that is thrown.
• The first except block that specifies the exact exception name of the thrown exception is executed. If
no except block specifies a matching exception name then an except block that does not have an
exception name is selected, if one is present in the code.
• For handling exception in Python, the exception handler block needs to be written which consists of
set of statements that need to be executed according to raised exception. There are three blocks that
are used in the exception handling process, namely, try, except and finally.
1. try Block: A set of statements that may cause error during runtime are to be written in the try
block.
2. except Block: It is written to display the execution details to the user when certain exception
occurs in the program. The except block executed only when a certain type as exception occurs in
the execution of statements written in the try block.
3. finally Block: This is the last block written while writing an exception handler in the program
which indicates the set of statements that many use to clean up to resources used by the
program.
Syntax:
try:
D the operations here
......................
except Exception1:
If there is Exception1, then execute this block.
except Exception2:
If there is Exception2, then execute this block.
......................
else:
If there is no exception then execute this block.
Example: For try-except clause/statement.
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
except IOError:
print ("Error: can\'t find file or read data")
else:
print ("Written content in the file successfully")
fh.close()
Example: For try statement.
n=10
m=0
try:
n/m
Programming with 'Python' 6.21 File I/O Handling and Exception Handling
except ZeroDivisionError:
print("Divide by zero error")
else:
print (n/m)
Output:
Divide by zero error
Enter an integer: 0
Error Occurred
Please enter valid value
Enter an integer: 5
Division is: 2.0
6.3.2.3 try…tinally
Programming with 'Python' 6.22 File I/O Handling and Exception Handling
• The try statement in Python can have an optional finally clause. This clause is executed no matter
what, and is generally used to release external resources.
• The statement written in finally clause will always be executed by the interpreter, whether the try
statement raises an exception or not.
• A finally block is always executed before leaving the try statement, whether an exception is occurred
or not. When an exception is occurred in try block and has not been handled by an except block, it is
re-raised after the finally block has been executed.
• The finally clause is also executed “on the way out” when any other clause of the try statement is left
via a break, continue or return statement.
Syntax:
try:
D the operations here;
......................
Due to any exception, this may be skipped.
finally:
This would always be executed.
......................
Example: For try-finally.
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
finally:
print ("file is closing")
fh.close()
Example: Program to check for ZeroDivisionError Exception.
x=int(input("Enter first value:"))
y=int(input("Enter second value:"))
try:
result=x/y
except ZeroDivisionError:
print("Division by Zero")
else:
print("Result is:",result)
finally:
print("Execute finally clause")
Output 1:
Enter first value:5
Enter second value:0
Division by Zero
Execute finally clause
Output 2:
Enter first value:10
Enter second value:5
Result is: 2.0
Execute finally clause
• We can raise an existing exception by using raise keyword. So, we just simply write raise keyword
and then the name of the exception.
• The raise statement allows the programmer to force a specified exception to occur.
• For example: We can use raise to throw an exception if age is less than 18 condition occurs.
while True:
try:
age = int(input("Enter your age for election: "))
if age < 18:
raise Exception
else:
print("you are eligible for election")
break
except Exception:
print("This value is too small, try again")
• Output:
Enter your age for election: 11
This value is too small, try again
Enter your age for election: 18
you are eligible for election
>>>
• The raise statement can be complemented with a custom exception as explained in next section.
6.3.4 User Defined Exception
• Python has many built-in exceptions which forces the program to output an error when something
in it goes wrong. However, sometimes we may need to create custom exceptions that serves the
purpose.
• Python allow programmers to create their own exception class. Exceptions should typically be
derived from the Exception class, either directly or indirectly. Most of the built-in exceptions are also
derived from Exception class.
• User can also create and raise his/her own exception known as user defined exception.
• In the following example, we create custom exception class AgeSmallException that is derived from
the base class Exception.
Example 1: Raise a user defined exception if age is less than 18.
# define Python user-defined exceptions
class Error(Exception):
"""Base class for other exceptions"""
pass
class AgeSmallException(Error):
"""Raised when the input value is too small"""
pass
# main program
while True:
try:
age = int(input("Enter your age for election: "))
if age < 18:
raise AgeSmallException
else:
print("you are eligible for election")
Programming with 'Python' 6.24 File I/O Handling and Exception Handling
break
except AgeSmallException:
print("This value is too small, try again!")
print()
Output:
Enter your age for election: 11
This value is too small, try again!
Enter your age for election: 15
This value is too small, try again!
Enter your age for election: 18
you are eligible for election
>>>
Example 2: Raise a user defined exception id password is incorrect.
class InvalidPassword(Exception):
pass
def verify_password(pswd):
if str(pswd) != "abc":
raise InvalidPassword
else:
print('Valid Password: '+str(pswd))
# main program
verify_password("abc") # won't raise exception
verify_password("xyz") # will raise exception
Output:
Valid Password: abc
Traceback (most recent call last):
File "C:\Users\Meenakshi\AppData\Local\Programs\Python\Python37\p1.py", line 12, in
<module>
verify_password("xyz") # will raise exception
File "C:\Users\Meenakshi\AppData\Local\Programs\Python\Python37\p1.py", line 6, in
verify_password
raise InvalidPassword
InvalidPassword
>>>
Practice Questions
1. What is file? Enlist types of files in Python programming.
2. What is exception?
3. Explain the term exception handling in detail.
4. Explain different modes of opening a file.
5. Write the syntax of fopen(). With example.
6. What are various modes of file object? Explain any five as them.
7. Explain exception handling with example using try, except, raise keywords.
8. Explain try…except blocks for exception handling in Python.
9. Explain various built in functions and methods.
10. Explain open() and close() methods for opening and closing a file.
Programming with 'Python' 6.25 File I/O Handling and Exception Handling