2.II-FIles_Exceptions & Modules Part-II 2022-23
2.II-FIles_Exceptions & Modules Part-II 2022-23
LECTURE NOTES
ON
PYTHON PROGRAMMING
R18 Regulation
Dr. N.Venkateswaran,
Associate Professor,
Opening a file
Python provides the open() function which 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.
The syntax to use the open() function is given below.
Let's look at the simple example to open a file named "file.txt" (stored in the same directory) in read mode
and printing its content on the console.
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 successfully
fileobject.close()
Consider the following example.
Example
# opens the file file.txt in read mode fileptr =
open("file.txt","r")
if fileptr:
print("file is opened successfully")
fileobj.read(<count>)
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);
Output:
<class 'str'>Hi, I am
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.readline();
fileptr.close()
Output:
<class 'str'>
Hi, I am the file and being used as
#running a
for loopfor i
in fileptr:
print(i) # i contains each line of the file
Output:
Hi, I am the file and being used as an
example to read a file in python.
Example 1
#open the file.txt in append mode. Creates a new file if no such file exists.
fileptr = open("file.txt","a");
print(fileptr)if fileptr:
print("File created successfully");
Output:
File created successfully
#after the read operation file pointer modifies. tell() returns the location of the fileptr.
Output:
The filepointer is at byte : 0
After reading, the filepointer is at 10
Python os module
The os module provides us the functions that are involved in file processing operations like renaming,
deleting, etc.
Let's look at some of the os module functions.
rename(?current-name?, ?new-name?)
Example
import os;
Deleting directory
The rmdir() method is used to delete the specified directory. The syntax to use the rmdir() method is given
below.os.rmdir(?directory name?)
Example
import os;
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.
2. NameError: It occurs when a name is not found. It may be local or global.
3. IndentationError: If incorrect indentation is given.
4. IOError: It occurs when Input Output operation fails.
5. EOFError: It occurs when the end of the file is reached, and yet operations are being performed.
Example
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b;
print("a/b = %d"%c)
#other code:
print("Hi I am other part of the program")
Output:
Enter a:10
Enter b:0
Traceback (most recent call last):
File "exception-test.py", line 3, in <module>
c = a/b;
ZeroDivisionError: division by zero
try:
#block of code
except Exception1:
#block of code
except Exception2:
#block of code
#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
Output:
Enter a:10
Enter b:2
a/b = 5
Hi I am else block
Example
try:
a = int(input("Enter a:"))
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")
Points to remember
1. Python facilitates us to not specify the exception with the except statement.
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.
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.
4. The statements that don't throw the exception should be placed inside the else block.
Example
try:
#this will throw an exception if the file doesn't exist.
fileptr = open("file.txt","r")
except IOError:
print("File not found")
else:
print("The file opened successfully")
fileptr.close()
Output:
File not found
Declaring multiple exceptions
The python allows us to declare the multiple exceptions with the except clause. Declaring multiple
exceptions is useful in the cases where a try block throws multiple exceptions.
Syntax
try:
#block of code
except (<Exception 1>,<Exception 2>,<Exception 3>,...<Exception n>)
#block of code
else:
#block of code
Example
try:
a=10/0;
except ArithmeticError,StandardError:
print "Arithmetic Exception"
else:
print "Successfully Done"
Output:
Prepared by Dr. N.Venkateswaran, Associate Professor, CSE Dept, JITS Page 9
Arithmetic Exception
Example
try:
fileptr = open("file.txt","r") try:
fileptr.write("Hi I am good") finally:
fileptr.close() print("file closed")
except:
print("Error")
Output:
file closed Error
Raising exceptions
An exception can be raised by using the raise clause in python. The syntax to use the raise statement is given
Examp
le
try:
age = int(input("Enter the age?"))
if age<18:
raise ValueError;
else:
print("the age is valid")
except ValueError:
print("The age is not valid")
Output:
Enter the age?17
The age is not valid
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?10Enter b?0
The value of b can't be 0
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 the Python object and classes.
try:
Prepared by Dr. N.Venkateswaran, Associate Professor, CSE Dept, JITS Page 11
raise ErrorInCode(2000)
except ErrorInCode as ae:
print("Received error:", ae.data)
Output:
Received error: 2000
Python Assertion
Python assert keyword is defined as a debugging tool that tests a condition. The Assertions are mainly the
assumption that asserts or state a fact confidently in the program. For example, while writing a division
function, the divisor should not be zero, and you assert that divisor is not equal to zero.
It is simply a boolean expression that has a condition or expression checks if the condition returns true
or false. If it is true, the program does not do anything, and it moves to the next line of code. But if it is false,
it raises an AssertionError exception with an optional error message.
The main task of assertions is to inform the developers about unrecoverable errors in the program like "file
not found", and it is right to say that assertions are internal self-checks for the program. They work by
declaring some conditions as impossible in your code. If one of the conditions does not hold, that means there
is a bug in the program.
Syntax
assert condition, error_message(optional)
Example1
This example shows the working of assert with the error message.
def avg(scores):
assert len(scores) != 0,"The List is empty."
return sum(scores)/len(scores)
scores2 = [67,59,86,75,92]
print("The Average of scores2:",avg(scores2))
scores1 = []
print("The Average of scores1:",avg(scores1))
Explanation: In the above example, we have passed a non-empty list scores2 and an empty list scores1 to
the avg() function. We received an output for scores2 list successfully, but after that, we got an error
AssertionError: List is empty.The assert condition is satisfied by the scores2 list and lets the program to
continue to run. However, scores1 doesn't satisfy the condition and gives an AssertionError.
Example2:
This example shows the "Divide by 0 error" in the console.
# initializing number
x=7
y=0
# It uses assert to check for 0
print ("x / y value is : ")
assert y != 0, "Divide by 0 error"
print (x / y)
Output:
x / y value is :
Runtime Exception :
Traceback (most recent call last):
File "main.py", line 6, in <module>
assert y != 0, "Divide by 0 error"
AssertionError: Divide by 0 error
Explanation: In the above example, we initialize an integer variable, i.e., x=7, y=0, and try to print the
value of x/y as an output. The compiler generates a Runtime Exception because of the assert keyword which
displays "Divide by 0 error" in the console.
The print statement will display if the entered number is greater than or equal to 0. Negative numbers result
in aborting the program after showing the AssertionError.
Result:
Enter a number: 100
You entered 100
The assert statement can optionally include an error message string, which gets displayed along with
the AssertionError. In the above code, you can change the assert statement to the following and run the code:
Example: assert
num=int(input('Enter a number: '))
assert num>=0, "Only positive numbers accepted."
print('You entered: ', num)
Result:
Enter a number: -10
Traceback (most recent call last):
File "C:/python36/xyz.py", line 2, in <module> assert
num>=0, "Only positive numbers accepted."AssertionError:
Only positive numbers accepted.
Python Modules
A python module can be defined as a python program file which contains a python code including python
functions, class, or variables. In other words, we can say that our python code file saved with the extension
(.py) is treated as the module. We may have a runnable code inside the python module.
Modules in Python provides us the flexibility to organize the code in a logical way.
To use the functionality of one module into another, we must have to import the specific module.
Example
In this example, we will create a module named as file.py which contains a function func that contains a
code to print some message on the console.
Let's create the module named as file.py.
#displayMsg prints a message to the name being passed.
def displayMsg(name) :
print("Hi "+name);
Here, we need to include this module into our main module to call the method displayMsg() defined in the
module named file.
We can import multiple modules with a single import statement, but a module is loaded once regardless of
the number of times, it has been imported into our file.
Example:
import file
name = input("Enter the name?")
file.displayMsg(name)
Output:
Enter the name?
John Hi John
Output:
The from...import statement is always better to use if we know the attributes to be imported from the module
in advance. It doesn't let our code to be heavier. We can also import all the attributes from a module by
using *.
Renaming a module
Python provides us the flexibility to import some module with a specific name so that we can use this name
to use that module in our python source file.
Example
1. import json
2.
3. List = dir(json)
Output:
['JSONDecoder', 'JSONEncoder', ' all ', ' author ', ' builtins ',
' cached ', ' doc ',
' file ', ' loader ', ' name ', ' package ', ' path ',
' spec ', ' version ',
'_default_decoder', '_default_encoder', 'decoder', 'dump', 'dumps',
'encoder', 'load', 'loads', 'scanner']
Scope of variables
In Python, variables are associated with two types of scopes. All the variables defined in a module contain
the global scope unless or until it is defined within a function.
All the variables defined inside a function contain a local scope that is limited to this function itself. We can
not access a local variable globally.
If two variables are defined with the same name with the two different scopes, i.e., local and global, then the
priority will always be given to the local variable.
Output:
Hi David
Let's create a package named Employees in your home directory. Consider the following steps.
1. Create a directory with name Employees on path /home.
2. Create a python source file with name ITEmployees.py on the path /home/Employees.
ITEmployees.py
1. def getITNames():
2. List = ["Varun", "Joel", "Shailu", "Snigdha"]
3. return List;
3. Similarly, create one more python file with name BPOEmployees.py and create a function
getBPONames().
4. Now, the directory Employees which we have created in the first step contains two python modules. To
make this directory a package, we need to include one more file here, that is init .py which contains the
import statements of the modules defined in this directory.
init .py
1. from ITEmployees import getITNames
2. from BPOEmployees import getBPONames
5. Now, the directory Employees has become the package containing two python modules. Here we must
notice that we must have to create init .py inside a directory to convert this directory to a package.
6. To use the modules defined inside the package Employees, we must have to import this in our python
source file. Let's create a simple python source file at our home directory (/home) which uses the modules
defined in this package.
Test.py
import Employees
print(Employees.getNames())
Output:
[‘Varun’, ‘Joel’, ‘Shailu’, ’Snigdha’]