6 PP 2024
6 PP 2024
TITLE: Write a program to demonstrate exception handling and file handling mechanism in
Python
CO1: Formulate a problem statement and develop the logic (algorithm/flowchart) for its
solution.
CO5: Apply the concept of exception handling and file handling in Python.
______________________________________________________________________
Theory:
What is Exception?
An exception is an event, which occurs during the execution of a program that disrupts
the normal flow of the program's instructions. In general, when a Python script
encounters a situation that it cannot cope with, it raises an exception. An exception is a
Python object that represents an error.
Department of Department of Science and Humanities
PP/I/July-November_2024_Page No.-____
K. J. Somaiya College of Engineering, Mumbai-77
When a Python script raises an exception, it must either handle the exception
immediately otherwise it terminates and quits.
Built-in Exceptions
Handling an exception
If you have some suspicious code that may raise an exception, you can defend your
program by placing the suspicious code in a try: block. After the try: block, include
an except: statement, followed by a block of code that handles the problem as elegantly
as possible.
The try-except else block:
Syntax:
try:
You do your operations here;
except ExceptionI:
If there is ExceptionI, then execute this block
else:
If there is no Exception, then execute this block
PP/I/July-November_2024_Page No.-____
K. J. Somaiya College of Engineering, Mumbai-77
Here are few important points about the above-mentioned syntax:
● A single try statement can have multiple except statements. This is useful when
the try block contains statements that may throw different types of exceptions.
● You can also provide a generic except clause, which handles any exception.
● After the except clause(s), you can include an else-clause. The code in the else-
block executes if the code in the try: block does not raise an exception.
● The else-block is a good place for code that does not need the try: block's
protection.
Example:
This example opens a file, writes content in the, file and comes out gracefully because
there is no problem at all
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()
This produces the following result:
Written content in the file successfully
Example:
This example tries to open a file where you do not have write permission, so it raises an
exception
try:
fh = open("testfile", "r")
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"
This produces the following result:
Error: can't find file or read data
PP/I/July-November_2024_Page No.-____
K. J. Somaiya College of Engineering, Mumbai-77
…………………..
except:
If there is any exception, then execute this block
………………………….
else
If there is no exception, then execute this block
…………………………….
This kind of a try-except statement catches all the exceptions that occur. Using this
kind of try-except statement is not considered a good programming practice though,
because it catches all exceptions but does not make the programmer identify the root
cause of the problem that may occur.
PP/I/July-November_2024_Page No.-____
K. J. Somaiya College of Engineering, Mumbai-77
If you do not have permission to open the file in writing mode, then this will produce
the following result
Error: can't find file or read data
The same example can be written more cleanly as follows:
try:
fh = open("testfile", "w")
try:
fh.write("This is my test file for exception handling!!")
finally:
print "Going to close the file"
fh.close()
except IOError:
print "Error: can\'t find file or read data"
When an exception is thrown in the try block, the execution immediately passes to
the finally block. After all the statements in the finally block are executed, the
exception is raised again and is handled in the except statements if present in the next
higher layer of the try-except statement.
try:
You do your operations here;
......................
except ExceptionType, Argument:
You can print value of Argument here...
If you write the code to handle a single exception, you can have a variable follow the
name of the exception in the except statement. If you are trapping multiple exceptions,
you can have a variable follow the tuple of the exception.
This variable receives the value of the exception mostly containing the cause of the
exception. The variable can receive a single value or multiple values in the form of a
tuple. This tuple usually contains the error string, the error number, and an error
location.
Example
Following is an example for a single exception
# Define a function here.
def temp_convert(var):
try:
return int(var)
except ValueError, Argument:
Department of Department of Science and Humanities
PP/I/July-November_2024_Page No.-____
K. J. Somaiya College of Engineering, Mumbai-77
print "The argument does not contain numbers\n", Argument
Raising an Exceptions:
You can raise exceptions in several ways by using the raise statement. The general
syntax for the raise statement is as follows.
Syntax:
raise [Exception [, args [, traceback]]]
Here, Exception is the type of exception (for example, NameError) and argument is a
value for the exception argument. The argument is optional; if not supplied, the
exception argument is None.
The final argument, traceback, is also optional (and rarely used in practice), and if
present, is the traceback object used for the exception.
Example
An exception can be a string, a class or an object. Most of the exceptions that the
Python core raises are classes, with an argument that is an instance of the class.
Defining new exceptions is quite easy and can be done as follows:
def functionName( level ):
if level < 1:
raise "Invalid level!", level
# The code below to this would not be executed
# if we raise the exception
Note: In order to catch an exception, an "except" clause must refer to
the same exception thrown either class object or simple string. For
example, to capture above exception, we must write the except
clause as follows −
try:
Business Logic here...
except "Invalid level!":
Exception handling here...
else:
Rest of the code here...
User-Defined Exceptions
Python also allows you to create your own exceptions by deriving classes from the
standard built-in exceptions.
Department of Department of Science and Humanities
PP/I/July-November_2024_Page No.-____
K. J. Somaiya College of Engineering, Mumbai-77
Here is an example related to RuntimeError. Here, a class is created that is subclassed
from RuntimeError. This is useful when you need to display more specific information
when an exception is caught.
In the try block, the user-defined exception is raised and caught in the except block.
The variable e is used to create an instance of the class Networkerror.
class Networkerror(RuntimeError):
def __init__(self, arg):
self.args = arg
So once you defined above class, you can raise the exception as
follows −
try:
raise Networkerror("Bad hostname")
except Networkerror e:
print e.args
Till now, we were taking the input from the console and writing it back to the console
to interact with the user.
Sometimes, it is not enough to only display the data on the console. The data to be
displayed may be very large, and only a limited amount of data can be displayed on the
console since the memory is volatile, it is impossible to recover the programmatically
generated data again and again.
The file handling plays an important role when the data needs to be stored permanently
in the file. A file is a named location on a disk to store related information. We can
access the stored information (non-volatile) after the program termination.
Open a file
Read or write - Performing operation
Close the file
Opening a file:
Python provides an open() function that accepts two arguments, file name and access
mode in which the file is accessed. The function returns a file object which can be used
to perform various operations like reading, writing, etc.
Syntax:
PP/I/July-November_2024_Page No.-____
K. J. Somaiya College of Engineering, Mumbai-77
file object = open(<file-name>, <access-mode>, <buffering>)
The files can be accessed using various modes like read, write, or append. The
following are the details about the access mode to open a file.
SN Access Description
mode
1 r It opens the file to read-only mode. The file pointer exists at the beginning. The
file is by default open in this mode if no access mode is passed.
2 rb It opens the file to read-only in binary format. The file pointer exists at the
beginning of the file.
3 r+ It opens the file to read and write both. The file pointer exists at the beginning of
the file.
4 rb+ It opens the file to read and write both in binary format. The file pointer exists at
the beginning of the file.
5 w It opens the file to write only. It overwrites the file if previously exists or creates a
new one if no file exists with the same name. The file pointer exists at the
beginning of the file.
6 wb It opens the file to write only in binary format. It overwrites the file if it exists
previously or creates a new one if no file exists. The file pointer exists at the
beginning of the file.
7 w+ It opens the file to write and read both. It is different from r+ in the sense that it
overwrites the previous file if one exists whereas r+ doesn't overwrite the
previously written file. It creates a new file if no file exists. The file pointer exists
at the beginning of the file.
8 wb+ It opens the file to write and read both in binary format. The file pointer exists at
the beginning of the file.
9 a It opens the file in the append mode. The file pointer exists at the end of the
previously written file if exists any. It creates a new file if no file exists with the
same name.
10 ab It opens the file in the append mode in binary format. The pointer exists at the end
of the previously written file. It creates a new file in binary format if no file exists
with the same name.
11 a+ It opens a file to append and read both. The file pointer remains at the end of the
file if a file exists. It creates a new file if no file exists with the same name.
PP/I/July-November_2024_Page No.-____
K. J. Somaiya College of Engineering, Mumbai-77
12 ab+ It opens a file to append and read both in binary format. The file pointer remains at
the end of the file.
Example:
#opens the file file.txt in read mode
fileptr = open("file.txt","r")
if fileptr:
print("file is opened successfully")
Output:
<class '_io.TextIOWrapper'>
file is opened successfullyProblem Definition:
In the above code, we have passed the filename as a first argument and opened file in
read mode as we mentioned r as the second argument. The fileptr holds the file object
and if the file is opened successfully, it will execute the print statement.
We can perform any operation on the file externally using the file system which is the
currently opened in Python; hence it is good practice to close the file once all the
operations are done.
Syntax:
fileobject.close()
Example:
try:
fileptr = open("file.txt")
# perform file operations
finally:
fileptr.close()
PP/I/July-November_2024_Page No.-____
K. J. Somaiya College of Engineering, Mumbai-77
The write() method does not add a newline character ('\n') to the end of the string
Syntax:
fileObject.write(string)
Example:
# Open a file
fo = open("foo.txt", "wb")
fo.write( "Python is a great language.\nYeah its great!!\n")
The above method would create foo.txt file and would write given content in that file
and finally it would close that file. If you would open this file, it would have following
content.
Output:
Python is a great language.
Yeah its great!!
Syntax:
fileObject.read([count])
Here, passed parameter is the number of bytes to be read from the opened file. This
method starts reading from the beginning of the file and if count is missing, then it tries
to read as much as possible, maybe until the end of file.
Example:
# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10);
print "Read String is : ", str
# Close opend file
fo.close()
Output
Read String is : Python is
File Positions
The tell() method tells you the current position within the file; in other words, the next
read or write will occur at that many bytes from the beginning of the file.
The seek(offset[, from]) method changes the current file position. The offset argument
indicates the number of bytes to be moved. The from argument specifies the reference
position from where the bytes are to be moved.
Department of Department of Science and Humanities
PP/I/July-November_2024_Page No.-____
K. J. Somaiya College of Engineering, Mumbai-77
If from is set to 0, it means use the beginning of the file as the reference position and 1
means use the current position as the reference position and if it is set to 2 then the end
of the file would be taken as the reference position.
Example:
# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10)
print "Read String is : ", str
To use this module you need to import it first and then you can call any related
functions.
Syntax:
os.rename(current_file_name, new_file_name)
Example:
Following is the example to rename an existing file test1.txt −
import os
Syntax:
os.remove(file_name)
Department of Department of Science and Humanities
PP/I/July-November_2024_Page No.-____
K. J. Somaiya College of Engineering, Mumbai-77
Example:
Following is the example to delete an existing file test2.txt −
import os
Problem Definition:
1. Write a program in which we prompt users to enter personal details like name
and surname, which should be strings, age should be an integer, and height and
weight should be float. Whenever the user enters input of the incorrect type,
keep prompting the user for the same value until it is entered correctly. Give the
user sensible feedback
Implementation details:
PP/I/July-November_2024_Page No.-____
K. J. Somaiya College of Engineering, Mumbai-77
Output(s):
Conclusion:
4. Write a program that prompts the user for a file name and then reads and prints
the contents of the requested file in the upper case.
PP/I/July-November_2024_Page No.-____