Unit VI File Handling and Exception Handling
Unit VI File Handling and Exception Handling
h
Unit VI
ik
File I/O Handling and Exception Handling
ha
.S
6a Write Python code for the given reading values from keyboard
6b Read data from the given file.
.A
1
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology & Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM
h
print("Python is fun.")
ik
a=5
# Two objects are passed
print("a =", a)
b=a ha
.S
# Three objects are passed
print('a =', a, '= b')
.A
Output
Python is fun.
a=5
.A
a=5=b
In the above program, only objects parameter is passed to print() function (in all three
of
print statements).
Hence,
Pr
i. ' ' separator is used. Notice, the space between two objects in output.
ii. end parameter '\n' (newline character) is used. Notice, each print statement
displays the output in the new line.
iii. file is sys.stdout. The output is printed on the screen.
iv. flush is False. The stream is not forcibly flushed.
Example 2: print() with separator and end parameters
a=5
print("a =", a, sep='00000', end='\n\n\n')
print("a =", a, sep='0', end='')
Output
a =000005
a =05
2
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology & Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM
h
The input([prompt]) function assumes the input is a valid Python expression and returns
ik
the evaluated result to you.
str = input("Enter your input: ")
ha
print ("Received input is : ", str)
This would produce the following result against the entered input −
.S
Enter your input: Hi
Recieved input is : Hi
.A
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.
1. Open a file
2. Read or write (perform operation)
3. Close the file
1. Opening a File
o Before you can read or write a file, you have to open it using Python's built-in
open() function.
o This function creates a file object, which would be utilized to call other support
methods associated with it.
o Syntax
file object = open(file_name [, access_mode][, buffering])
3
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology & Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM
h
Sr.No. Modes Description
ik
1 r Opens a file for reading only. The file pointer is placed at
ha
the beginning of the file. This is the default mode.
2 rb Opens a file for reading only in binary format. The file
pointer is placed at the beginning of the file. This is the
.S
default mode.
3 r+ Opens a file for both reading and writing. The file pointer
placed at the beginning of the file.
.A
4 rb+ Opens a file for both reading and writing in binary format.
The file pointer placed at the beginning of the file.
.A
5 w Opens a file for writing only. Overwrites the file if the file
exists. If the file does not exist, creates a new file for
writing.
of
4
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology & Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM
h
Sr.No. Attribute Description
1 file.closed Returns true if file is closed, false otherwise.
ik
2 file.mode Returns access mode with which file was opened.
ha
3 file.name Returns name of the file.
4 file.softspace Returns false if space explicitly required with
print, true otherwise.
.S
Example
.A
# Open a file
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name
.A
5
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology & Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM
Here, the count is the number of bytes to be read from the file starting from the beginning
of the file. If the count is not specified, then it may read the content of the file until the
end.
Consider the following example.
Example
#open the file.txt in read mode. causes error if no such file exists.
fileptr = open("file.txt","r");
#stores all the data of the file into the variable content
content = fileptr.read(9);
# prints the type of the data stored in the file
print(type(content))
#prints the content of the file
print(content)
h
#closes the opened file
fileptr.close()
ik
Output:
ha
<class 'str'>
Hi, I am
.S
Read Lines of the file
Python facilitates us to read the file line by line by using a function readline().
.A
The readline() method reads the lines of the file from the beginning, i.e., if we use the
readline() method two times, then we can get the first two lines of the file.
.A
Consider the following example which contains a function readline() that reads the first
line of our file "file.txt" containing three lines.
Example
of
#open the file.txt in read mode. causes error if no such file exists.
Pr
fileptr = open("file.txt","r");
#stores all the data of the file into the variable content
content = fileptr.readline();
# prints the type of the data stored in the file
print(type(content))
#prints the content of the file
print(content)
#closes the opened file
fileptr.close()
Output:
<class 'str'>
Hi, I am the file and being used as
6
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology & Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM
h
Writing the file
To write some text to a file, we need to open the file using the open method with one of
ik
the following access modes.
ha
a: It will append the existing file. The file pointer is at the end of the file. It
creates a new file if no file exists.
.S
w: It will overwrite the file if any file exists. The file pointer is at the beginning of
the file.
Consider the following example.
.A
#open the file.txt in append mode. Creates a new file if no such file exists.
fileptr = open("file.txt","a");
.A
7
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology & Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM
h
with open(<file name>, <access mode>) as <file-pointer>:
ik
#statement suite
The advantage of using with statement is that it provides the guarantee to close the file
ha
regardless of how the nested block exits.
It is always suggestible to use the with statement in the case of file s because, if the break,
.S
return, or exception occurs in the nested block of code then it automatically closes the
file. It doesn't let the file to be corrupted.
Consider the following example.
.A
with open("file.txt",'r') as f:
content = f.read();
.A
print(content)
Output:
of
8
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology & Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM
Output:
The filepointer is at byte : 0
After reading, the filepointer is at 26
h
2. from: It indicates the reference position from where the bytes are to be moved. If it is
ik
set to 0, the beginning of the file is used as the reference position. If it is set to 1, the
current position of the file pointer is used as the reference position. If it is set to 2, the
ha
end of the file pointer is used as the reference position.
Consider the following example.
.S
# open the file file2.txt in read mode
fileptr = open("file2.txt","r")
#initially the filepointer is at 0
.A
fileptr.seek(10);
#tell() returns the location of the fileptr.
of
9
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology & Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM
This method is not entirely safe. If an exception occurs when we are performing some
operation with the file, the code exits without closing the file.
A safer way is to use a try...finally block.
try:
f = open("test.txt", 'r')
# perform file operations
finally:
f.close()
Python Directory
If there are a large number of files to handle in your Python program, you can arrange
your code within different directories to make things more manageable.
A directory or folder is a collection of files and sub directories. Python has the os module,
h
which provides us with many useful methods to work with directories (and files as well).
ik
Get Current Directory
We can get the present working directory using the getcwd() method.
ha
This method returns the current working directory in the form of a string. We can also
use the getcwdb() method to get it as bytes object.
.S
Example
import os
.A
print(os.getcwd())
Output
D:\WPy32-3741\settings
.A
Changing Directory
We can change the current working directory using the chdir() method.
of
The new path that we want to change to must be supplied as a string to this method. We
can use both forward slash (/) or the backward slash (\) to separate path elements.
Pr
10
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology & Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM
h
reset.exe', 'Spyder.exe', 't', 'temp1.py', 'VS Code.exe', 'we.py', 'WinPython
Command Prompt.exe', 'WinPython Control Panel.exe', 'WinPython
ik
Interpreter.exe', 'WinPython Powershell Prompt.exe']
ha
Making a New Directory
We can make a new directory using the mkdir() method.
.S
This method takes in the path of the new directory. If the full path is not specified, the
new directory is created in the current working directory.
Example
.A
import os
os.mkdir('test')
.A
print(os.listdir())
Output
of
11
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology & Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM
h
'file1.py', 'file2.py', 'filebuilt.py', 'fileread.py', 'fr.py', 'fun1.py', 'fwrite.py', 'hj.py',
'ma.py', 'meh.py', 'mehtodoverride.py', 'mehtodoverride1.py', 'methodoverload.py',
ik
'mod1.py', 'multilevel.py', 'nam.py', 'new_one', 'nonpara.py', 'print.py',
ha
'pydistutils.cfg', 'raw.py', 'runtime', 'sam.py', 'sam1.py', 'sample.py', 'sample.txt',
'sample1.txt', 'sd.py', 'sdf.py', 'seaborn-data', 'simple_package', 'test.py',
.S
'winpython.ini', 'xc.py', '__pycache__']
Example
import os
of
os.remove('sd.py')
print("After File Removeing")
print(os.listdir())
print("After Directory Removeing")
os.rmdir('new_one')
print(os.listdir())
Output
Before File Removeing Before Directory Removeing
['.config', '.idlerc', '.ipython', '.jupyter', '.matplotlib', '.ptpython', '.pyzo', '.spyder-
py3', 'as.py', 'as12.py', 'ash.txt', 'cal.py', 'calculation.py', 'callmod.py', 'classattr.py',
'classattri.py', 'classfun.py', 'classinh.py', 'classsample.py', 'constpara.py',
'countobj.py', 'datahide.py', 'deci.py', 'ds.py', 'erew.py', 'f1.py', 'f3.py', 'file.py',
'file1.py', 'file2.py', 'filebuilt.py', 'fileread.py', 'fr.py', 'fun1.py', 'fwrite.py', 'hj.py',
12
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology & Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM
h
'sample1.txt', 'sdf.py', 'seaborn-data', 'simple_package', 'winpython.ini', 'xc.py',
ik
'__pycache__']
ha
After Directory Removeing
['.config', '.idlerc', '.ipython', '.jupyter', '.matplotlib', '.ptpython', '.pyzo', '.spyder-
.S
py3', 'as.py', 'as12.py', 'ash.txt', 'cal.py', 'calculation.py', 'callmod.py', 'classattr.py',
'classattri.py', 'classfun.py', 'classinh.py', 'classsample.py', 'constpara.py',
'countobj.py', 'datahide.py', 'deci.py', 'ds.py', 'erew.py', 'f1.py', 'f3.py', 'file.py',
.A
However, note that rmdir() method can only remove empty directories.
Pr
In order to remove a non-empty directory we can use the rmtree() method inside
the shutil module.
Example
import shutil
shutil.rmtree('simple_package')
13
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology & Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM
Python Exceptions
An exception can be defined as an abnormal condition in a program resulting in the
disruption in the flow of the program.
Whenever an exception occurs, the program halts the execution, and thus the further code
is not executed. Therefore, an exception is the error which python script is unable to
tackle with.
Python provides us with the way to handle the Exception so that the other part of the code
can be executed without any disruption. However, if we do not handle the exception, the
interpreter doesn't execute all the code that exists after the that.
Common Exceptions
A list of common exceptions that can be thrown from a normal python program is given
below.
1. ZeroDivisionError: Occurs when a number is divided by zero.
h
2. NameError: It occurs when a name is not found. It may be local or global.
ik
3. IndentationError: If incorrect indentation is given.
4. IOError: It occurs when Input Output operation fails.
ha
5. EOFError: It occurs when the end of the file is reached, and yet operations are
being performed.
.S
Problem without handling exceptions
As we have already discussed, the exception is an abnormal condition that halts the
.A
b = int(input("Enter b:"))
c = a/b;
of
print("a/b = %d"%c)
#other code:
Pr
14
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology & Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM
h
ik
ha
.S
Syntax
try:
#block of code
.A
except Exception1:
.A
#block of code
except Exception2:
of
#block of code
Pr
#other code
We can also use the else statement with the try-except statement in which, we can place
the code which will be executed in the scenario if no exception occurs in the try block.
The syntax to use the else statement with the try-except statement is given below.
try:
#block of code
except Exception1:
#block of code
else:
#this code executes if no except block is executed
15
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology & Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM
h
ik
ha
.S
Example
try:
a = int(input("Enter a:"))
.A
b = int(input("Enter b:"))
c = a/b;
.A
print("a/b = %d"%c)
except Exception:
of
16
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology & Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM
b = int(input("Enter b:"))
c = a/b;
print("a/b = %d"%c)
except:
print("can't divide by zero")
else:
print("Hi I am else block")
Output:
Enter a:10
Enter b:0
can't divide by zero
Points to remember
h
1. Python facilitates us to not specify the exception with the except statement.
ik
2. We can declare multiple exceptions in the except statement since the try block may
contain the statements which throw the different type of exceptions.
ha
3. We can also specify an else block along with the try-except statement which will be
executed if no exception is raised in the try block.
.S
4. The statements that don't throw the exception should be placed inside the else block.
.A
Syntax
try:
of
#block of code
Pr
h
ik
ha
.S
.A
.A
of
Pr
18
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology & Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM
Example
try:
fileptr = open("file.txt","r")
try:
fileptr.write("Hi I am good")
finally:
fileptr.close()
print("file closed")
except:
print("Error")
Output:
h
file closed
Error
ik
ha
.S
Raising exceptions
An exception can be raised by using the raise clause in python. The syntax to use the
raise statement is given below.
.A
syntax
raise Exception_class,<value>
.A
Points to remember
1. To raise an exception, raise statement is used. The exception class name follows it.
of
2. An exception can be provided with a value that can be given in the parenthesis.
3. To access the value "as" keyword is used. "e" is used as a reference variable which stores
Pr
19
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology & Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM
Example
try:
a = int(input("Enter a?"))
b = int(input("Enter b?"))
if b is 0:
raise ArithmeticError;
else:
print("a/b = ",a/b)
except ArithmeticError:
print("The value of b can't be 0")
Output:
Enter a?10
h
Enter b?0
ik
The value of b can't be 0
ha
.S
Custom Exception
The python allows us to create our exceptions that can be raised from the program and
caught using the except clause. However, we suggest you read this section after visiting
.A
Example
class ErrorInCode(Exception):
def __init__(self, data):
of
self.data = data
Pr
def __str__(self):
return repr(self.data)
try:
raise ErrorInCode(2000)
except ErrorInCode as ae:
print("Received error:", ae.data)
Output:
Received error: 2000
20