0% found this document useful (0 votes)
18 views

Python Unit2 - Watermark

Python notes

Uploaded by

hihi95174
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Python Unit2 - Watermark

Python notes

Uploaded by

hihi95174
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

File Handling

As the part of programming requirement, we have to store our data permanently for
future purpose. For this requirement we should go for files.

Files are very common permanent storage areas to store our data.

Types of Files:
There are 2 types of files

1. Text Files:

Usually we can use text files to store character data


eg: abc.txt

2. Binary Files:

Usually we can use binary files to store binary data like images,video files, audio files etc...

Opening a File:
Before performing any operation (like read or write) on the file,first we have to open that
file.For this we should use Python's inbuilt function open()

But at the time of open, we have to specify mode,which represents the purpose of
opening file.

f = open(filename, mode)

The allowed modes in Python are

1. r  open an existing file for read operation. The file pointer is positioned at the
beginning of the file.If the specified file does not exist then we will get
FileNotFoundError.This is default mode.
2. w  open an existing file for write operation. If the file already contains some data
then it will be overridden. If the specified file is not already avaialble then this mode will
create that file.

3. a  open an existing file for append operation. It won't override existing data.If the
specified file is not already avaialble then this mode will create a new file.

4. r+  To read and write data into the file. The previous data in the file will not be
deleted.The file pointer is placed at the beginning of the file.

5. w+  To write and read data. It will override existing data.

6. a+  To append and read data from the file.It wont override existing data.

7. x  To open a file in exclusive creation mode for write operation. If the file already
exists then we will get FileExistsError.

Note: All the above modes are applicable for text files. If the above modes suffixed with
'b' then these represents for binary files.

Eg: rb,wb,ab,r+b,w+b,a+b,xb

f = open("abc.txt","w")

We are opening abc.txt file for writing data.

Closing a File:
After completing our operations on the file,it is highly recommended to close the file.
For this we have to use close() function.

f.close()

Various properties of File Object:


Once we opend a file and we got file object,we can get various details related to that file
by using its properties.

name  Name of opened file


mode  Mode in which the file is opened
closed  Returns boolean value indicates that file is closed or not
readable() Retruns boolean value indicates that whether file is readable or not
writable() Returns boolean value indicates that whether file is writable or not.
Eg:

1) f=open("abc.txt",'w')
2) print("File Name: ",f.name)
3) print("File Mode: ",f.mode)
4) print("Is File Readable: ",f.readable())
5) print("Is File Writable: ",f.writable())
6) print("Is File Closed : ",f.closed)
7) f.close()
8) print("Is File Closed : ",f.closed)
9)
10)
11) Output
12) D:\Python_classes>py test.py
13) File Name: abc.txt
14) File Mode: w
15) Is File Readable: False
16) Is File Writable: True
17) Is File Closed : False
18) Is File Closed : True

Writing data to text files:


We can write character data to the text files by using the following 2 methods.

write(str)
writelines(list of lines)

Eg:

1) f=open("abcd.txt",'w')
2) f.write("Durga\n")
3) f.write("Software\n")
4) f.write("Solutions\n")
5) print("Data written to the file successfully")
6) f.close()

abcd.txt:
Durga
Software
Solutions

Note: In the above program, data present in the file will be overridden everytime if we
run the program. Instead of overriding if we want append operation then we should open
the file as follows.

f = open("abcd.txt","a")
Eg 2:

1) f=open("abcd.txt",'w')
2) list=["sunny\n","bunny\n","vinny\n","chinny"]
3) f.writelines(list)
4) print("List of lines written to the file successfully")
5) f.close()

abcd.txt:
sunny
bunny
vinny
chinny

Note: while writing data by using write() methods, compulsory we have to provide line
seperator(\n),otherwise total data should be written to a single line.

Reading Character Data from text files:


We can read character data from text file by using the following read methods.

read() To read total data from the file


read(n)  To read 'n' characters from the file
readline() To read only one line
readlines() To read all lines into a list

Eg 1: To read total data from the file

1) f=open("abc.txt",'r')
2) data=f.read()
3) print(data)
4) f.close()
5)
6) Output
7) sunny
8) bunny
9) chinny
10) vinny

Eg 2: To read only first 10 characters:

1) f=open("abc.txt",'r')
2) data=f.read(10)
3) print(data)
4) f.close()
5)
6) Output
7) sunny
8) bunn

Eg 3: To read data line by line:

1) f=open("abc.txt",'r')
2) line1=f.readline()
3) print(line1,end='')
4) line2=f.readline()
5) print(line2,end='')
6) line3=f.readline()
7) print(line3,end='')
8) f.close()
9)
10) Output
11) sunny
12) bunny
13) chinny

Eg 4: To read all lines into list:

1) f=open("abc.txt",'r')
2) lines=f.readlines()
3) for line in lines:
4) print(line,end='')
5) f.close()
6)
7) Output
8) sunny
9) bunny
10) chinny
11) vinny

Eg 5:

1) f=open("abc.txt","r")
2) print(f.read(3))
3) print(f.readline())
4) print(f.read(4))
5) print("Remaining data")
6) print(f.read())
7)
8) Output
9) sun
10) ny
11)
12) bunn
13) Remaining data
14) y
15) chinny
16) vinny

The with statement:


The with statement can be used while opening a file.We can use this to group file
operation statements within a block.
The advantage of with statement is it will take care closing of file,after completing all
operations automatically even in the case of exceptions also, and we are not required to
close explicitly.
Eg:

1) with open("abc.txt","w") as f:
2) f.write("hii\n")
3) f.write("Soft\n")
4) f.write("\n")
5) print("Is File Closed: ",f.closed)
6) print("Is File Closed: ",f.closed)
7)
8) Output
9) Is File Closed: False
10) Is File Closed: True

The seek() and tell() methods:

tell():

==>We can use tell() method to return current position of the cursor(file pointer) from
beginning of the file. [ can you plese telll current cursor position]
The position(index) of first character in files is zero just like string index.

Eg:

1) f=open("abc.txt","r")
2) print(f.tell())
3) print(f.read(2))
4) print(f.tell())
5) print(f.read(3))
6) print(f.tell())

abc.txt:
sunny
bunny
chinny
vinny
Output:
0
su
2
nny
5

seek():

We can use seek() method to move cursor(file pointer) to specified location.


[Can you please seek the cursor to a particular location]

f.seek(offset, fromwhere)

offset represents the number of positions

The allowed values for second attribute(from where) are


0--- >From beginning of file(default value)
1 >From current position
2 >From end of the file

Note: Python 2 supports all 3 values but Python 3 supports only zero.

Eg:

1) data="All Students are practicing programs"


2) f=open("abc.txt","w")
3) f.write(data)
4) with open("abc.txt","r+") as f:
5) text=f.read()
6) print(text)
7) print("The Current Cursor Position: ",f.tell())
8) f.seek(17)
9) print("The Current Cursor Position: ",f.tell())
10) f.write("GEMS!!!")
11) f.seek(0)
12) text=f.read()
13) print("Data After Modification:")
14) print(text)
15)
16) Output
17)
18) All Students are STUPIDS
19) The Current Cursor Position: 24
20) The Current Cursor Position: 17
21) Data After Modification:
22) All Students are GEMS!!!

How to check a particular file exists or not?

We can use os library to get information about files in our computer.


os module has path sub module,which contains isFile() function to check whether a
particular file exists or not?
os.path.isfile(fname)

Q. Write a program to check whether the given file exists or not. If it is


available then print its content?

1) import os,sys
2) fname=input("Enter File Name: ")
3) if os.path.isfile(fname):
4) print("File exists:",fname)
5) f=open(fname,"r")
6) else:
7) print("File does not exist:",fname)
8) sys.exit(0)
9) print("The content of file is:")
10) data=f.read()
11) print(data)
12)
13) Output
14) D:\Python_classes>py test.py
15) Enter File Name: durga.txt
16) File does not exist: durga.txt
17)
18) D:\Python_classes>py test.py
19) Enter File Name: abc.txt
20) File exists: abc.txt
21) The content of file is:
22) All Students are GEMS!!!
23) All Students are GEMS!!!
24) All Students are GEMS!!!
25) All Students are GEMS!!!
26) All Students are GEMS!!!
27) All Students are GEMS!!!

Note:
sys.exit(0) ===>To exit system without executing rest of the program.
argument represents status code . 0 means normal termination and it is the default value.
Q. Program to print the number of lines,words and characters present in the
given file?

1) import os,sys
2) fname=input("Enter File Name: ")
3) if os.path.isfile(fname):
4) print("File exists:",fname)
5) f=open(fname,"r")
6) else:
7) print("File does not exist:",fname)
8) sys.exit(0)
9) lcount=wcount=ccount=0
10) for line in f:
11) lcount=lcount+1
12) ccount=ccount+len(line)
13) words=line.split()
14) wcount=wcount+len(words)
15) print("The number of Lines:",lcount)
16) print("The number of Words:",wcount)
17) print("The number of Characters:",ccount)
18)
19) Output
20) D:\Python_classes>py test.py
21) Enter File Name: durga.txt
22) File does not exist: durga.txt
23)
24) D:\Python_classes>py test.py
25) Enter File Name: abc.txt
26) File exists: abc.txt
27) The number of Lines: 6
28) The number of Words: 24
29) The number of Characters: 149

abc.txt:

All Students are GEMS!!!


All Students are GEMS!!!
All Students are GEMS!!!
All Students are GEMS!!!
All Students are GEMS!!!
All Students are GEMS!!!
Handling Binary Data:
It is very common requirement to read or write binary data like images,video files,audio
files etc.

Q. Program to read image file and write to a new image file?

1) f1=open("rossum.jpg","rb")
2) f2=open("newpic.jpg","wb")
3) bytes=f1.read()
4) f2.write(bytes)
5) print("New Image is available with the name: newpic.jpg")

Handling csv files:


CSV==>Comma seperated values

As the part of programming,it is very common requirement to write and read data wrt csv
files. Python provides csv module to handle csv files.

Writing data to csv file:


1) import csv
2) with open("emp.csv","w",newline='') as f:
3) w=csv.writer(f) # returns csv writer object
4) w.writerow(["ENO","ENAME","ESAL","EADDR"])
5) n=int(input("Enter Number of Employees:"))
6) for i in range(n):
7) eno=input("Enter Employee No:")
8) ename=input("Enter Employee Name:")
9) esal=input("Enter Employee Salary:")
10) eaddr=input("Enter Employee Address:")
11) w.writerow([eno,ename,esal,eaddr])
12) print("Total Employees data written to csv file successfully")

Note: Observe the difference with newline attribute and without

with open("emp.csv","w",newline='') as f:
with open("emp.csv","w") as f:

Note: If we are not using newline attribute then in the csv file blank lines will be included
between data. To prevent these blank lines, newline attribute is required in Python-3,but
in Python-2 just we can specify mode as 'wb' and we are not required to use newline
attribute.
Reading Data from csv file:
1) import csv
2) f=open("emp.csv",'r')
3) r=csv.reader(f) #returns csv reader object
4) data=list(r)
5) #print(data)
6) for line in data:
7) for word in line:
8) print(word,"\t",end='')
9) print()
10)
11) Output
12) D:\Python_classes>py test.py
13) ENO ENAME ESAL EADDR
14) 100 Durga 1000 Hyd
15) 200 Sachin 2000 Mumbai
16) 300 Dhoni 3000 Ranchi

Zipping and Unzipping Files:

It is very common requirement to zip and unzip files.


The main advantages are:

1. To improve memory utilization


2. We can reduce transport time
3. We can improve performance.

To perform zip and unzip operations, Python contains one in-bulit module zip file.
This module contains a class : ZipFile

To create Zip file:

We have to create ZipFile class object with name of the zip file,mode and constant
ZIP_DEFLATED. This constant represents we are creating zip file.

f = ZipFile("files.zip","w","ZIP_DEFLATED")

Once we create ZipFile object,we can add files by using write() method.

f.write(filename)
Eg:

1) from zipfile import *


2) f=ZipFile("files.zip",'w',ZIP_DEFLATED)
3) f.write("file1.txt")
4) f.write("file2.txt")
5) f.write("file3.txt")
6) f.close()
7) print("files.zip file created successfully")

To perform unzip operation:

We have to create ZipFile object as follows

f = ZipFile("files.zip","r",ZIP_STORED)

ZIP_STORED represents unzip operation. This is default value and hence we are not
required to specify.
Once we created ZipFile object for unzip operation,we can get all file names present in
that zip file by using namelist() method.

names = f.namelist()

Eg:

1) from zipfile import *


2) f=ZipFile("files.zip",'r',ZIP_STORED)
3) names=f.namelist()
4) for name in names:
5) print( "File Name: ",name)
6) print("The Content of this file is:")
7) f1=open(name,'r')
8) print(f1.read())
9) print()

Working with Directories:

It is very common requirement to perform operations for directories like

1. To know current working directory


2. To create a new directory
3. To remove an existing directory
4. To rename a directory
5. To list contents of the directory
etc...
To perform these operations,Python provides inbuilt module os,which contains several
functions to perform directory related operations.

Q1. To Know Current Working Directory:

import os
cwd=os.getcwd()
print("Current Working Directory:",cwd)

Q2. To create a sub directory in the current working directory:

import os
os.mkdir("mysub")
print("mysub directory created in cwd")

Q3. To create a sub directory in mysub directory:

cwd
|-mysub
|-mysub2

import os
os.mkdir("mysub/mysub2")
print("mysub2 created inside mysub")

Note: Assume mysub already present in cwd.

Q4. To create multiple directories like sub1 in that sub2 in that sub3:

import os
os.makedirs("sub1/sub2/sub3")
print("sub1 and in that sub2 and in that sub3 directories created")

Q5. To remove a directory:

import os
os.rmdir("mysub/mysub2")
print("mysub2 directory deleted")

Q6. To remove multiple directories in the path:

import os
os.removedirs("sub1/sub2/sub3")
print("All 3 directories sub1,sub2 and sub3 removed")
Q7. To rename a directory:

import os
os.rename("mysub","newdir")
print("mysub directory renamed to newdir")

Q8. To know contents of directory:

os module provides listdir() to list out the contents of the specified directory. It won't
display the contents of sub directory.

Eg:

1) import os
2) print(os.listdir("."))
3)
4) Output
5) D:\Python_classes>py test.py
6) ['abc.py', 'abc.txt', 'abcd.txt', 'com', 'demo.py', 'durgamath.py', 'emp.csv', '
7) file1.txt', 'file2.txt', 'file3.txt', 'files.zip', 'log.txt', 'module1.py', 'myl
8) og.txt', 'newdir', 'newpic.jpg', 'pack1', 'rossum.jpg', 'test.py', ' pycache '
9) ]

The above program display contents of current working directory but not contents of sub
directories.

If we want the contents of a directory including sub directories then we should go for
walk() function.

Q9. To know contents of directory including sub directories:

We have to use walk() function


[Can you please walk in the directory so that we can aware all contents of that directory]

os.walk(path,topdown=True,onerror=None,followlinks=False)

It returns an Iterator object whose contents can be displayed by using for loop

path-->Directory path. cwd means .


topdown=True --->Travel from top to bottom
onerror=None --->on error detected which function has to execute.
followlinks=True -->To visit directories pointed by symbolic links
Eg: To display all contents of Current working directory including sub directories:
1) import os
2) for dirpath,dirnames,filenames in os.walk('.'):
3) print("Current Directory Path:",dirpath)
4) print("Directories:",dirnames)
5) print("Files:",filenames)
6) print()
7)
8)
9) Output
10) Current Directory Path: .
11) Directories: ['com', 'newdir', 'pack1', ' pycache ']
12) Files: ['abc.txt', 'abcd.txt', 'demo.py', 'durgamath.py', 'emp.csv', 'file1.txt'
13) , 'file2.txt', 'file3.txt', 'files.zip', 'log.txt', 'module1.py', 'mylog.txt', '
14) newpic.jpg', 'rossum.jpg', 'test.py']
15)
16) Current Directory Path: .\com
17) Directories: ['durgasoft', ' pycache ']
18) Files: ['module1.py', ' init .py']
19)
20) ...

Note: To display contents of particular directory,we have to provide that directory name
as argument to walk() function.

os.walk("directoryname")

Q. What is the difference between listdir() and walk() functions?

In the case of listdir(), we will get contents of specified directory but not sub directory
contents. But in the case of walk() function we will get contents of specified directory and
its sub directories also.

Running Other programs from Python program:

os module contains system() function to run programs and commands.


It is exactly same as system() function in C language.

os.system("commad string")
The argument is any command which is executing from DOS.

Eg:
import os
os.system("dir *.py")
os.system("py abc.py")
How to get information about a File:

We can get statistics of a file like size, last accessed time,last modified time etc by using
stat() function of os module.

stats = os.stat("abc.txt")

The statistics of a file includes the following parameters:

st_mode==>Protection Bits
st_ino==>Inode number
st_dev===>device
st_nlink===>no of hard links
st_uid===>userid of owner
st_gid==>group id of owner
st_size===>size of file in bytes
st_atime==>Time of most recent access
st_mtime==>Time of Most recent modification
st_ctime==> Time of Most recent meta data change

Note:

st_atime, st_mtime and st_ctime returns the time as number of milli seconds since Jan 1st
1970 ,12:00AM. By using datetime module fromtimestamp() function,we can get exact
date and time.

Q. To print all statistics of file abc.txt:

1) import os
2) stats=os.stat("abc.txt")
3) print(stats)
4)
5) Output
6) os.stat_result(st_mode=33206, st_ino=844424930132788, st_dev=2657980798, st_nlin
7) k=1, st_uid=0, st_gid=0, st_size=22410, st_atime=1505451446, st_mtime=1505538999
8) , st_ctime=1505451446)

Q. To print specified properties:

1) import os
2) from datetime import *
3) stats=os.stat("abc.txt")
4) print("File Size in Bytes:",stats.st_size)
5) print("File Last Accessed Time:",datetime.fromtimestamp(stats.st_atime))
6) print("File Last Modified Time:",datetime.fromtimestamp(stats.st_mtime))
7)
8) Output
9) File Size in Bytes: 22410
10) File Last Accessed Time: 2017-09-15 10:27:26.599490
11) File Last Modified Time: 2017-09-16 10:46:39.245394

Pickling and Unpickling of Objects:


Sometimes we have to write total state of object to the file and we have to read total
object from the file.

The process of writing state of object to the file is called pickling and the process of
reading state of an object from the file is called unpickling.

We can implement pickling and unpickling by using pickle module of Python.

pickle module contains dump() function to perform pickling.

pickle.dump(object,file)

pickle module contains load() function to perform unpickling

obj=pickle.load(file)

pickling
pickle.dump
eno: 100 (e1, f)
ename: Durga
esal: 10000
eaddr: HYD
e1 eno: 100
ename: Durga
esal: 10000
eaddr: HYD

eno: 100 abc.txt


ename: Durga pickle load (f)
esal: 10000
eaddr: HYD unpickling
e2
Writing and Reading State of object by using pickle Module:
1) import pickle
2) class Employee:
3) def init (self,eno,ename,esal,eaddr):
4) self.eno=eno;
5) self.ename=ename;
6) self.esal=esal;
7) self.eaddr=eaddr;
8) def display(self):
9) print(self.eno,"\t",self.ename,"\t",self.esal,"\t",self.eaddr)
10) with open("emp.dat","wb") as f:
11) e=Employee(100,"Durga",1000,"Hyd")
12) pickle.dump(e,f)
13) print("Pickling of Employee Object completed...")
14)
15) with open("emp.dat","rb") as f:
16) obj=pickle.load(f)
17) print("Printing Employee Information after unpickling")
18) obj.display()

Writing Multiple Employee Objects to the file:

emp.py:

1) class Employee:
2) def init (self,eno,ename,esal,eaddr):
3) self.eno=eno;
4) self.ename=ename;
5) self.esal=esal;
6) self.eaddr=eaddr;
7) def display(self):
8)
9) print(self.eno,"\t",self.ename,"\t",self.esal,"\t",self.eaddr)

pick.py:

1) import emp,pickle
2) f=open("emp.dat","wb")
3) n=int(input("Enter The number of Employees:"))
4) for i in range(n):
5) eno=int(input("Enter Employee Number:"))
6) ename=input("Enter Employee Name:")
7) esal=float(input("Enter Employee Salary:"))
8) eaddr=input("Enter Employee Address:")
9) e=emp.Employee(eno,ename,esal,eaddr)
10) pickle.dump(e,f)
11) print("Employee Objects pickled successfully")
unpick.py:

1) import emp,pickle
2) f=open("emp.dat","rb")
3) print("Employee Details:")
4) while True:
5) try:
6) obj=pickle.load(f)
7) obj.display()
8) except EOFError:
9) print("All employees Completed")
10) break
11) f.close()
Exception Handling
In any programming language there are 2 types of errors are possible.

1. Syntax Errors
2. Runtime Errors

1. Syntax Errors:

The errors which occurs because of invalid syntax are called syntax errors.

Eg 1:

x=10
if x==10
print("Hello")

SyntaxError: invalid syntax

Eg 2:
print "Hello"

SyntaxError: Missing parentheses in call to 'print'

Note:
Programmer is responsible to correct these syntax errors. Once all syntax errors are
corrected then only program execution will be started.

2. Runtime Errors:

Also known as exceptions.


While executing the program if something goes wrong because of end user input or
programming logic or memory problems etc then we will get Runtime Errors.

Eg: print(10/0) ==>ZeroDivisionError: division by zero

print(10/"ten") ==>TypeError: unsupported operand type(s) for /: 'int' and 'str'

x=int(input("Enter Number:"))
print(x)

D:\Python_classes>py test.py

DURGASOFT, # 202, 2ndFloor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,


1
Enter Number:ten
ValueError: invalid literal for int() with base 10: 'ten'

Note: Exception Handling concept applicable for Runtime Errors but not for syntax errors

What is Exception:
An unwanted and unexpected event that disturbs normal flow of program is called
exception.

Eg:

ZeroDivisionError
TypeError
ValueError
FileNotFoundError
EOFError
SleepingError
TyrePuncturedError

It is highly recommended to handle exceptions. The main objective of exception handling


is Graceful Termination of the program(i.e we should not block our resources and we
should not miss anything)

Exception handling does not mean repairing exception. We have to define alternative way
to continue rest of the program normally.

Eg:

For example our programming requirement is reading data from remote file locating at
London. At runtime if london file is not available then the program should not be
terminated abnormally. We have to provide local file to continue rest of the program
normally. This way of defining alternative is nothing but exception handling.

try:

read data from remote file locating at london


except FileNotFoundError:
use local file and continue rest of the program normally

Q. What is an Exception?
Q. What is the purpose of Exception Handling?
Q. What is the meaning of Exception Handling?

DURGASOFT, # 202, 2ndFloor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,


2
Default Exception Handing in Python:
Every exception in Python is an object. For every exception type the corresponding classes
are available.

Whevever an exception occurs PVM will create the corresponding exception object and
will check for handling code. If handling code is not available then Python interpreter
terminates the program abnormally and prints corresponding exception information to
the console.
The rest of the program won't be executed.

Eg:

1) print("Hello")
2) print(10/0)
3) print("Hi")
4)
5) D:\Python_classes>py test.py
6) Hello
7) Traceback (most recent call last):
8) File "test.py", line 2, in <module>
9) print(10/0)
10) ZeroDivisionError: division by zero
Python's Exception Hierarchy
BaseException

Exception SystemExit GeneratorExit KeyboardInterrupt

Attribute Arithmetic EOF Name Lookup OS Type Value


Error Error Error Error Error Error Error Error

ZeroDivision Index FileNotFound


Error Error Error

FloatingPoint Key Interrupted


Error Error Error

Overflow Permission
Error Error

TimeOut
Error

Every Exception in Python is a class.


All exception classes are child classes of BaseException.i.e every exception class extends
BaseException either directly or indirectly. Hence BaseException acts as root for Python
Exception Hierarchy.

Most of the times being a programmer we have to concentrate Exception and its child
classes.

Customized Exception Handling by using try-except:

It is highly recommended to handle exceptions.


The code which may raise exception is called risky code and we have to take risky code
inside try block. The corresponding handling code we have to take inside except block.
try:
Risky Code
except XXX:
Handling code/Alternative Code

without try-except:

1. print("stmt-1")
2. print(10/0)
3. print("stmt-3")
4.
5. Output
6. stmt-1
7. ZeroDivisionError: division by zero

Abnormal termination/Non-Graceful Termination

with try-except:

1. print("stmt-1")
2. try:
3. print(10/0)
4. except ZeroDivisionError:
5. print(10/2)
6. print("stmt-3")
7.
8. Output
9. stmt-1
10. 5.0
11. stmt-3

Normal termination/Graceful Termination

Control Flow in try-except:


try:
stmt-1
stmt-2
stmt-3
except XXX:
stmt-4
stmt-5

case-1: If there is no exception


1,2,3,5 and Normal Termination
case-2: If an exception raised at stmt-2 and corresponding except block matched
1,4,5 Normal Termination

case-3: If an exception raised at stmt-2 and corresponding except block not matched
1, Abnormal Termination

case-4: If an exception raised at stmt-4 or at stmt-5 then it is always abnormal


termination.

Conclusions:
1. within the try block if anywhere exception raised then rest of the try block wont be
executed eventhough we handled that exception. Hence we have to take only risky code
inside try block and length of the try block should be as less as possible.

2. In addition to try block,there may be a chance of raising exceptions inside except and
finally blocks also.

3. If any statement which is not part of try block raises an exception then it is always
abnormal termination.

How to print exception information:


try:

1. print(10/0)
2. except ZeroDivisionError as msg:
3. print("exception raised and its description is:",msg)
4.
5. Output exception raised and its description is: division by zero

try with multiple except blocks:

The way of handling exception is varied from exception to exception.Hence for every
exception type a seperate except block we have to provide. i.e try with multiple except
blocks is possible and recommended to use.

Eg:
try:
-------
-------
-------
except ZeroDivisionError:
perform alternative
arithmetic operations
except FileNotFoundError:
use local file instead of remote file

If try with multiple except blocks available then based on raised exception the
corresponding except block will be executed.

Eg:

1) try:
2) x=int(input("Enter First Number: "))
3) y=int(input("Enter Second Number: "))
4) print(x/y)
5) except ZeroDivisionError :
6) print("Can't Divide with Zero")
7) except ValueError:
8) print("please provide int value only")
9)
10) D:\Python_classes>py test.py
11) Enter First Number: 10
12) Enter Second Number: 2
13) 5.0
14)
15) D:\Python_classes>py test.py
16) Enter First Number: 10
17) Enter Second Number: 0
18) Can't Divide with Zero
19)
20) D:\Python_classes>py test.py
21) Enter First Number: 10
22) Enter Second Number: ten
23) please provide int value only

If try with multiple except blocks available then the order of these except blocks is
important .Python interpreter will always consider from top to bottom until matched
except block identified.

Eg:

1) try:
2) x=int(input("Enter First Number: "))
3) y=int(input("Enter Second Number: "))
4) print(x/y)
5) except ArithmeticError :
6) print("ArithmeticError")
7) except ZeroDivisionError:
8) print("ZeroDivisionError")
9)
10) D:\Python_classes>py test.py
11) Enter First Number: 10
12) Enter Second Number: 0
13) ArithmeticError

Single except block that can handle multiple exceptions:

We can write a single except block that can handle multiple different types of exceptions.

except (Exception1,Exception2,exception3,..): or
except (Exception1,Exception2,exception3,..) as msg :

Parenthesis are mandatory and this group of exceptions internally considered as tuple.

Eg:

1) try:
2) x=int(input("Enter First Number: "))
3) y=int(input("Enter Second Number: "))
4) print(x/y)
5) except (ZeroDivisionError,ValueError) as msg:
6) print("Plz Provide valid numbers only and problem is: ",msg)
7)
8) D:\Python_classes>py test.py
9) Enter First Number: 10
10) Enter Second Number: 0
11) Plz Provide valid numbers only and problem is: division by zero
12)
13) D:\Python_classes>py test.py
14) Enter First Number: 10
15) Enter Second Number: ten
16) Plz Provide valid numbers only and problem is: invalid literal for int() with b
17) ase 10: 'ten'

Default except block:


We can use default except block to handle any type of exceptions.
In default except block generally we can print normal error messages.

Syntax:
except:
statements
Eg:

1) try:
2) x=int(input("Enter First Number: "))
3) y=int(input("Enter Second Number: "))
4) print(x/y)
5) except ZeroDivisionError:
6) print("ZeroDivisionError:Can't divide with zero")
7) except:
8) print("Default Except:Plz provide valid input only")
9)
10) D:\Python_classes>py test.py
11) Enter First Number: 10
12) Enter Second Number: 0
13) ZeroDivisionError:Can't divide with zero
14)
15) D:\Python_classes>py test.py
16) Enter First Number: 10
17) Enter Second Number: ten
18) Default Except:Plz provide valid input only

***Note: If try with multiple except blocks available then default except block should be
last,otherwise we will get SyntaxError.

Eg:

1) try:
2) print(10/0)
3) except:
4) print("Default Except")
5) except ZeroDivisionError:
6) print("ZeroDivisionError")
7)
8) SyntaxError: default 'except:' must be last

Note:

The following are various possible combinations of except blocks


1. except ZeroDivisionError:
1. except ZeroDivisionError as msg:
3. except (ZeroDivisionError,ValueError) :
4. except (ZeroDivisionError,ValueError) as msg:
5. except :

finally block:

1. It is not recommended to maintain clean up code(Resource Deallocating Code or


Resource Releasing code) inside try block because there is no guarentee for the execution
of every statement inside try block always.

2. It is not recommended to maintain clean up code inside except block, because if there
is no exception then except block won't be executed.
Hence we required some place to maintain clean up code which should be executed
always irrespective of whether exception raised or not raised and whether exception
handled or not handled. Such type of best place is nothing but finally block.

Hence the main purpose of finally block is to maintain clean up code.

try:
Risky Code
except:
Handling Code
finally:
Cleanup code

The speciality of finally block is it will be executed always whether exception raised or not
raised and whether exception handled or not handled.

Case-1: If there is no exception


1) try:
2) print("try")
3) except:
4) print("except")
5) finally:
6) print("finally")
7)
8) Output
9) try
10) finally

Case-2: If there is an exception raised but handled:


1) try:
2) print("try")
3) print(10/0)
4) except ZeroDivisionError:
5) print("except")
6) finally:
7) print("finally")
8)
9) Output
10) try
11) except
12) finally
Case-3: If there is an exception raised but not handled:
1) try:
2) print("try")
3) print(10/0)
4) except NameError:
5) print("except")
6) finally:
7) print("finally")
8)
9) Output
10) try
11) finally
12) ZeroDivisionError: division by zero(Abnormal Termination)

*** Note: There is only one situation where finally block won't be executed ie whenever
we are using os._exit(0) function.

Whenever we are using os._exit(0) function then Python Virtual Machine itself will be
shutdown.In this particular case finally won't be executed.

1) imports
2) try:
3) print("try")
4) os._exit(0)
5) except NameError:
6) print("except")
7) finally:
8) print("finally")
9)
10) Output
11) try

Note:
os._exit(0)
where 0 represents status code and it indicates normal termination
There are multiple status codes are possible.

Control flow in try-except-finally:


try:
stmt-1
stmt-2
stmt-3
except:
stmt-4
finally:
stmt-5
stmt6

Case-1: If there is no exception


1,2,3,5,6 Normal Termination

Case-2: If an exception raised at stmt2 and the corresponding except block matched
1,4,5,6 Normal Termination

Case-3: If an exception raised at stmt2 but the corresponding except block not matched
1,5 Abnormal Termination

Case-4:If an exception raised at stmt4 then it is always abnormal termination but before
that finally block will be executed.

Case-5: If an exception raised at stmt-5 or at stmt-6 then it is always abnormal


termination

Nested try-except-finally blocks:

We can take try-except-finally blocks inside try or except or finally blocks.i.e nesting of try-
except-finally is possible.

try:
----------
----------
----------
try:
-------------
--------------
--------------
except:
--------------
--------------
--------------
------------
except:
-----------
-----------
-----------
General Risky code we have to take inside outer try block and too much risky code we
have to take inside inner try block. Inside Inner try block if an exception raised then inner
except block is responsible to handle. If it is unable to handle then outer except block is
responsible to handle.

Eg:

1) try:
2) print("outer try block")
3) try:
4) print("Inner try block")
5) print(10/0)
6) except ZeroDivisionError:
7) print("Inner except block")
8) finally:
9) print("Inner finally block")
10) except:
11) print("outer except block")
12) finally:
13) print("outer finally block")
14)
15) Output
16) outer try block
17) Inner try block
18) Inner except block
19) Inner finally block
20) outer finally block

Control flow in nested try-except-finally:


try:
stmt-1
stmt-2
stmt-3
try:
stmt-4
stmt-5
stmt-6
except X:
stmt-7
finally:
stmt-8
stmt-9
except Y:
stmt-10
finally:
stmt-11
stmt-12
case-1: If there is no exception
1,2,3,4,5,6,8,9,11,12 Normal Termination

case-2: If an exception raised at stmt-2 and the corresponding except block matched
1,10,11,12 Normal Termination

case-3: If an exceptiion raised at stmt-2 and the corresponding except block not matched
1,11,Abnormal Termination

case-4: If an exception raised at stmt-5 and inner except block matched


1,2,3,4,7,8,9,11,12 Normal Termination

case-5: If an exception raised at stmt-5 and inner except block not matched but outer
except block matched

1,2,3,4,8,10,11,12,Normal Termination

case-6:If an exception raised at stmt-5 and both inner and outer except blocks are not
matched

1,2,3,4,8,11,Abnormal Termination

case-7: If an exception raised at stmt-7 and corresponding except block matched


1,2,3,.,.,.,8,10,11,12,Normal Termination

case-8: If an exception raised at stmt-7 and corresponding except block not matched
1,2,3,.,.,.,8,11,Abnormal Termination

case-9: If an exception raised at stmt-8 and corresponding except block matched


1,2,3,.,.,.,.,10,11,12 Normal Termination

case-10: If an exception raised at stmt-8 and corresponding except block not matched
1,2,3,.,.,.,.,11,Abnormal Termination

case-11: If an exception raised at stmt-9 and corresponding except block matched


1,2,3,.,.,.,.,8,10,11,12,Normal Termination

case-12: If an exception raised at stmt-9 and corresponding except block not matched
1,2,3,.,.,.,.,8,11,Abnormal Termination

case-13: If an exception raised at stmt-10 then it is always abonormal termination but


before abnormal termination finally block(stmt-11) will be executed.
case-14: If an exception raised at stmt-11 or stmt-12 then it is always abnormal
termination.

Note: If the control entered into try block then compulsary finally block will be executed.
If the control not entered into try block then finally block won't be executed.

else block with try-except-finally:


We can use else block with try-except-finally blocks.
else block will be executed if and only if there are no exceptions inside try block.

try:
Risky Code
except:
will be executed if exception inside try
else:
will be executed if there is no exception inside try
finally:
will be executed whether exception raised or not raised and handled or not
handled

Eg:

try:
print("try")
print(10/0)--->1
except:
print("except")
else:
print("else")
finally:
print("finally")

If we comment line-1 then else block will be executed b'z there is no exception inside try.
In this case the output is:

try
else
finally

If we are not commenting line-1 then else block won't be executed b'z there is exception
inside try block. In this case output is:
try
except
finally

Various possible combinations of try-except-else-finally:


1. Whenever we are writing try block, compulsory we should write except or finally
block.i.e without except or finally block we cannot write try block.

2. Wheneever we are writing except block, compulsory we should write try block. i.e
except without try is always invalid.

3. Whenever we are writing finally block, compulsory we should write try block. i.e finally
without try is always invalid.

4. We can write multiple except blocks for the same try,but we cannot write multiple
finally blocks for the same try

5. Whenever we are writing else block compulsory except block should be there. i.e
without except we cannot write else block.

6. In try-except-else-finally order is important.

7. We can define try-except-else-finally inside try,except,else and finally blocks. i.e nesting
of try-except-else-finally is always possible.

try:
1
print("try") 
except:
2
print("Hello") 
else:
3
print("Hello") 
finally:
4
print("Hello") 
try:
print("try")
5
except: √
print("except")
try:
print("try")
6
finally: √
print("finally")
try:
7
print("try") √
except:
print("except")
else:
print("else")
try:
print("try")
8
else: 
print("else")
try:
print("try")
else:
9
print("else") 
finally:
print("finally")
try:
print("try")
except XXX:
10
print("except-1") √
except YYY:
print("except-2")
try:
print("try")
except :
print("except-1")
11
else: 
print("else")
else:
print("else")
try:
print("try")
except :
print("except-1")
12
finally: 
print("finally")
finally:
print("finally")
try:
print("try")
13 print("Hello") 
except:
print("except")
try:
14 print("try") 
except:
print("except")
print("Hello")
except:
print("except")
try:
print("try")
except:
15 print("except") 
print("Hello")
finally:
print("finally")
try:
print("try")
except:
16 print("except") 
print("Hello")
else:
print("else")
try:
print("try")
except:
print("except")
17
try: √
print("try")
except:
print("except")
try:
print("try")
except:
print("except")
18
try: √
print("try")
finally:
print("finally")
try:
print("try")
except:
print("except")
19
if 10>20: 
print("if")
else:
print("else")
try:
20
print("try") √
try:
print("inner try")
except:
print("inner except block")
finally:
print("inner finally block")
except:
print("except")
try:
print("try")

except:
print("except")
21 try:
print("inner try")

except:
print("inner except block")
finally:
print("inner finally block")
try:
print("try")
except:
print("except")
finally:
22 try:
print("inner try")

except:
print("inner except block")
finally:
print("inner finally block")
try:
print("try")
except:
print("except")
23
try: 
print("try")
else:
print("else")
try:
print("try")
try:
24
print("inner try") 
except:
print("except")
try:
print("try")
else:
print("else")
25
except: 
print("except")
finally:
print("finally")

Types of Exceptions:
In Python there are 2 types of exceptions are possible.
1. Predefined Exceptions
2. User Definded Exceptions

1. Predefined Exceptions:

Also known as in-built exceptions

The exceptions which are raised automatically by Python virtual machine whenver a
particular event occurs, are called pre defined exceptions.

Eg 1: Whenever we are trying to perform Division by zero, automatically Python will raise
ZeroDivisionError.
print(10/0)

Eg 2: Whenever we are trying to convert input value to int type and if input value is not
int value then Python will raise ValueError automatically

x=int("ten")===>ValueError

2. User Defined Exceptions:

Also known as Customized Exceptions or Programatic Exceptions

Some time we have to define and raise exceptions explicitly to indicate that something
goes wrong ,such type of exceptions are called User Defined Exceptions or Customized
Exceptions

Programmer is responsible to define these exceptions and Python not having any idea
about these. Hence we have to raise explicitly based on our requirement by using "raise"
keyword.
Eg:
InSufficientFundsException
InvalidInputException
TooYoungException
TooOldException

How to Define and Raise Customized Exceptions:

Every exception in Python is a class that extends Exception class either directly or
indirectly.

Syntax:
class classname(predefined exception class name):
def init (self,arg):
self.msg=arg

Eg:

1) class TooYoungException(Exception):
2) def init (self,arg):
3) self.msg=arg

TooYoungException is our class name which is the child class of Exception

We can raise exception by using raise keyword as follows


raise TooYoungException("message")

Eg:

1) class TooYoungException(Exception):
2) def init (self,arg):
3) self.msg=arg
4)
5) class TooOldException(Exception):
6) def init (self,arg):
7) self.msg=arg
8)
9) age=int(input("Enter Age:"))
10) if age>60:
11) raise TooYoungException("Plz wait some more time you will get best match soon!!!")
12) elif age<18:
13) raise TooOldException("Your age already crossed marriage age...no chance of getting ma
rriage")
14) else:
15) print("You will get match details soon by email!!!")
16)
17) D:\Python_classes>py test.py

nd
18) Enter Age:90
19) main .TooYoungException: Plz wait some more time you will get best match soon!!!
20)
21) D:\Python_classes>py test.py
22) Enter Age:12
23) main .TooOldException: Your age already crossed marriage age...no chance of g
24) etting marriage
25)
26) D:\Python_classes>py test.py
27) Enter Age:27
28) You will get match details soon by email!!!

Note:
raise keyword is best suitable for customized exceptions but not for pre defined
exceptions

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy