Professional Documents
Culture Documents
Unit No. 6
File I/O handling
and Exception
handling
by
P. S. Bhandare
Hours: 06
Marks: 12
1|Page
Prashant S. Bhandare
Unit VI: File I/O handling and Exception handling Programming with “Python” (22616)
Syllabus:
6.1 I/O Operations: Reading keyboard input, Printing to screen
6.2 File Handling: Opening file in different modes, accessing file contents
using standard library functions, Reading and writing files, closing a file,
Renaming and deleting files, Directories in Python, File and directory
related standard functions
6.3 Exception Handling: Introduction, Exception handling 'try: except:'
statement, 'raise' statement, User defined exceptions
2|Page
Prashant S. Bhandare
Unit VI: File I/O handling and Exception handling Programming with “Python” (22616)
3|Page
Prashant S. Bhandare
Unit VI: File I/O handling and Exception handling Programming with “Python” (22616)
4|Page
Prashant S. Bhandare
Unit VI: File I/O handling and Exception handling Programming with “Python” (22616)
For example, if you want to show the values in a loop, you can use the end= keyword
argument to display them all in one line.
for n in range(15):
print(n, end=' ')
Output Formatting
Although the above two keyword arguments are useful to format the output string, they
only help us change the spacing or decide what will come at the end of the output.
However, we can use the str.format() method to get more precise control over the
appearance of data.
a = 'mine'; b = 'yours'
print ('This book is {} and that pen is {}' . format(a,b))
We can also use the tuple index (numbers) to specify the order.
print('He ate {0} and {1}'.format('chocolate','ice cream'))
print('He ate {1} and {0}'.format('chocolate','ice cream'))
Python Input
To run an application, programmers often need to obtain input in Python from a user. The
simplest way to do this is to use the input() function. The function pauses program
execution to let the user type a line of information from the keyboard. When the user hits
“Enter”, the input is read and returned as a string.
We follow the given syntax to use the input() function:
input([<prompt>])
Here, the prompt is an optional string that we wish to display for the user.
>>>name = input ('What is your name? - ')
>>>print ('Hello,', name)
What is your name? - John
Hello, John
By default, the input() function accepts only string arguments. However, we can this to a
number by using the int() of float() functions
>>>number = input ('What is your number? ')
5|Page
Prashant S. Bhandare
Unit VI: File I/O handling and Exception handling Programming with “Python” (22616)
6|Page
Prashant S. Bhandare
Unit VI: File I/O handling and Exception handling Programming with “Python” (22616)
Prog.1:
# a file named "geek", will be opened with the reading mode.
file = open('geek.txt', 'r')
Prog.2:
# Python code to illustrate read() mode
file = open("geeks.txt", "r")
print (file.read())
Output:
Hello world
GeeksforGeeks
123 456
Prog.3:
# Python code to illustrate with()
with open("geeks.txt") as file:
data = file.read()
print(data)
output:
Hello world
GeeksforGeeks
123 456
Another way to read a file is to call a certain number of characters like in the
following code the interpreter will read the first five characters of stored data
and return it as a string:
Prog.4:
# Python code to illustrate read() mode character wise
file = open("geeks.txt", "r")
print (file.read(5))
Output:
Hello
Prog.5:
# Python code to illustrate split() function
with open("geeks.txt", "r") as file:
data = file.readlines()
for line in data:
word = line.split()
print (word)
8|Page
Prashant S. Bhandare
Unit VI: File I/O handling and Exception handling Programming with “Python” (22616)
Output:
['Hello', 'world']
['GeeksforGeeks']
['123', '456']
Creating a File using the write() Function
Just like reading a file in Python, there are a number of ways to Writing to file in
Python. Let us see how we can write the content of a file using the write()
function in Python.
# Python code to create a file
file = open('geek.txt','w')
file.write("This is the write command")
file.write("It allows us to write in a particular file")
file.close()
We can also use the written statement along with the with() function.
# Python code to illustrate with() alongwith write()
with open("file.txt", "w") as f:
f.write("Hello World!!!")
9|Page
Prashant S. Bhandare
Unit VI: File I/O handling and Exception handling Programming with “Python” (22616)
The desired name for the new directory is passed as the parameter.
By default it creates the new directory in the current working directory.
If the new directory has to be created somewhere else then that path has to be
specified and the path should contain forward slashes instead of backward
ones.
import os
# creates in current working directory
os.mkdir('new_dir')
# creates in D:\
os.mkdir('D:/new_dir')
import os
print("String format :", os.getcwd())
print("Byte string format :", os.getcwdb())
Renaming a directory:
os.rename() method is used to rename the directory.
The parameters passed are old_name followed by new_name.
If a directory already exists with the new_name passed, OSError will be
raised in case of both Unix and Windows.
If a file already exists with the new_name, in Unix no error arises, the
directory will be renamed. But in Windows the renaming won’t happen and
error will be raised.
os.renames(‘old_name’,’dest_dir:/new_name’) method works similar
to os.rename() but it moves the renamed file to the specified destination
directory(dest_dir).
import os
os.rename('file1.txt','file1_renamed.txt')
10 | P a g e
Prashant S. Bhandare
Unit VI: File I/O handling and Exception handling Programming with “Python” (22616)
import os
print("Current directory :", os.getcwd())
# Changing directory
os.chdir('/home/nikhil/Desktop/')
print("Current directory :", os.getcwd())
Listing the files in a directory
A directory may contain sub-directories and a number of files in it. To
list them, os.listdir() method is used.
It either takes no parameter or one parameter.
If no parameter is passed, then the files and sub-directories of the
CWD is listed.
If files of any other directory other than the CWD is required to be
listed, then that directory’s name/path is passed as parameter.
import os
print("The files in CWD are :",os.listdir(os.getcwd()))
Removing a directory
os.rmdir() method is used to remove/delete a directory.
The parameter passed is the path to that directory.
It deletes the directory if and only if it is empty, otherwise raises an
OSError.
import os
dir_li=os.listdir('k:/files')
if len(dir_li)==0:
print("Error!! Directory not empty!!")
else:
os.rmdir('k:/files')
11 | P a g e
Prashant S. Bhandare
Unit VI: File I/O handling and Exception handling Programming with “Python” (22616)
print(os.getcwd())
# Output: C:\Program Files\PyScripter
Here, getcwd() returns the current directory in the form of a string.
Changing Directory in Python
In Python, we can change the current working directory by using
the chdir() method.
The new path that we want to change into must be supplied as a string to this
method. And we can use both the forward-slash / or the backward-slash \ to
separate the path elements.
Let's see an example,
import os
# change directory
os.chdir('C:\\Python33')
print(os.getcwd())
Output: C:\Python33
Here, we have used the chdir() method to change the current working
directory and passed a new path as a string to chdir().
List Directories and Files in Python
All files and sub-directories inside a directory can be retrieved using
the listdir() method.
This method takes in a path and returns a list of subdirectories and files in
that path. If no path is specified, it returns the list of subdirectories and files
from the current working directory.
import os
print(os.getcwd())
C:\Python33
# list all sub-directories
os.listdir()
['DLLs',
'Doc',
'include',
12 | P a g e
Prashant S. Bhandare
Unit VI: File I/O handling and Exception handling Programming with “Python” (22616)
'Lib',
'libs',
'LICENSE.txt',
'NEWS.txt',
'python.exe',
'pythonw.exe',
'README.txt',
'Scripts',
'tcl',
'Tools']
os.listdir('G:\\')
['$RECYCLE.BIN',
'Movies',
'Music',
'Photos',
'Series',
'System Volume Information']
Making a New Directory in Python
In Python, we can make a new directory using the mkdir() method.
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.
os.mkdir('test')
os.listdir()
['test']
14 | P a g e
Prashant S. Bhandare
Unit VI: File I/O handling and Exception handling Programming with “Python” (22616)
Python Exceptions
When a Python program meets an error, it stops the execution of the rest of the
program. An error in Python might be either an error in the syntax of an
expression or a Python exception. We will see what an exception is. Also, we will
see the difference between a syntax error and an exception in this tutorial.
Following that, we will learn about trying and except blocks and how to raise
exceptions and make assertions. After that, we will see the Python exceptions list.
What is an Exception?
When a Python code throws an exception, it has two options: handle the
exception immediately or stop and quit.
When the interpreter identifies a statement that has an error, syntax errors occur.
Consider the following scenario:
#Python code after removing the syntax error
string = "Python Exceptions"
for s in string:
if (s != o:
print( s )
Output:
if (s != o:
^
SyntaxError: invalid syntax
Example2:
string = "Python Exceptions"
for s in string:
if (s != o):
print( s )
15 | P a g e
Prashant S. Bhandare
Unit VI: File I/O handling and Exception handling Programming with “Python” (22616)
Output:
2 string = "Python Exceptions"
4 for s in string:
----> 5 if (s != o):
6 print( s )
NameError: name 'o' is not defined
In Python, we catch exceptions and handle them using try and except code blocks. The
try clause contains the code that can raise an exception, while the except clause contains
the code lines that handle the exception. Let's see if we can access the index from the
array, which is more than the array's length, and handle the resulting exception.
# Python code to catch an exception and handle it using try and except code blocks
a = ["Python", "Exceptions", "try and except"]
try:
#looping through the elements of the array a, choosing a range that goes beyo
nd the length of the array
for i in range( 4 ):
print( "The index and element from the array is", i, a[i] )
#if an error occurs in the try block, then except block will be executed by the Pyth
on interpreter
except:
print ("Index out of range")
Output:
The code blocks that potentially produce an error are inserted inside the
try clause in the preceding example. The value of i greater than 2 attempts
to access the list's item beyond its length, which is not present, resulting in
an exception. The except clause then catches this exception and executes
code without stopping it.
16 | P a g e
Prashant S. Bhandare
Unit VI: File I/O handling and Exception handling Programming with “Python” (22616)
If a condition does not meet our criteria but is correct according to the Python
interpreter, we can intentionally raise an exception using the raise keyword. We can use
a customized exception in conjunction with the statement.
Output:
1 num = [3, 4, 5, 7]
2 if len(num) > 3:
----> 3 raise Exception( f"Length of the given list must be less than or equal to 3 but is
{len(num)}" )
Exception: Length of the given list must be less than or equal to 3 but is 4
Assertions in Python
Python examines the adjacent expression, preferably true when it finds an assert
statement. Python throws an AssertionError exception if the result of the expression is
false.
17 | P a g e
Prashant S. Bhandare
Unit VI: File I/O handling and Exception handling Programming with “Python” (22616)
Output:
Python also supports the else clause, which should come after every except clause, in
the try, and except blocks. Only when the try clause fails to throw an exception the
Python interpreter goes on to the else block.
# Python program to show how to use else clause with try and except clauses
# Defining a function which returns reciprocal of a number
def reciprocal( num1 ):
try:
reci = 1 / num1
except ZeroDivisionError:
18 | P a g e
Prashant S. Bhandare
Unit VI: File I/O handling and Exception handling Programming with “Python” (22616)
Output:
0.25
We cannot divide by zero
Finally Keyword in Python
The finally keyword is available in Python, and it is always used after the try-
except block. The finally code block is always executed after the try block has
terminated normally or after the try block has terminated for some other reason.
Output:
User-Defined Exceptions
By inheriting classes from the typical built-in exceptions, Python also lets us design our
customized exceptions.
19 | P a g e
Prashant S. Bhandare
Unit VI: File I/O handling and Exception handling Programming with “Python” (22616)
We raise a user-defined exception in the try block and then handle the exception in the
except block. An example of the class EmptyError is created using the variable var.
class EmptyError( RuntimeError ):
def __init__(self, argument):
self.arguments = argument
Once the preceding class has been created, the following is how to raise an
exception:
Code
var = " "
try:
raise EmptyError( "The variable is empty" )
except (EmptyError, var):
print( var.arguments )
2 try:
----> 3 raise EmptyError( "The variable is empty" )
4 except (EmptyError, var):
20 | P a g e
Prashant S. Bhandare
Unit VI: File I/O handling and Exception handling Programming with “Python” (22616)
8 ZeroDivisionError For all numeric data types, its value is raised whenever a
number is attempted to be divided by zero.
16 KeyError When the given key is not found in the dictionary to be found
in, this exception is raised.
21 | P a g e
Prashant S. Bhandare
Unit VI: File I/O handling and Exception handling Programming with “Python” (22616)
20 IOError If an input or output action fails, like when using the print
command or the open() function to access a file that does not
exist, this exception is raised.
Syntax:
try:
# Code block
# These statements are those which can probably have some error
except:
# This block is optional.
# If the try block encounters an exception, this block will handle it.
else:
22 | P a g e
Prashant S. Bhandare
Unit VI: File I/O handling and Exception handling Programming with “Python” (22616)
For each try block, there can be zero or more except blocks.
Multiple except blocks allow us to handle each exception differently. The
argument type of each except block indicates the type of exception that can be
handled by it. For example,
try:
even_numbers = [2,4,6,8]
print(even_numbers[5])
except ZeroDivisionError:
except IndexError:
23 | P a g e
Prashant S. Bhandare