Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
84 views59 pages

Computer Science - File Handling

Uploaded by

r.nitheshkannaa
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)
84 views59 pages

Computer Science - File Handling

Uploaded by

r.nitheshkannaa
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/ 59

File Handling

➢ File Handling allows Users to handle Files, that is to read and


write on the files.
➢ File Handling is necessary in any language and its helps us to
create and write files for permanent storage.
Data Files:
Text Files.
Binary Files.
Text Files:
❖ Always in Human readable format,
❖ It stores information in ASCII and Unicode
characters.
❖ Extension of Text File is “ Filename.txt,FN.dat”
Binary Files:
➢ Always in Machine Readable format
➢ It Stores the Data in Binary Format(0’s and 1’s)
➢ Extension of Binary File is “ Filename.dat, Filename.bin ”, etc.
➢ Open() and Close():
Open() Function is used to open a File.
<file_object >= open(<"filename", "mode“>)
eg:
myfile=open(“file1.txt”)
myfile=open(“file1.txt”,”r”)
Single & Double Slash:
f=open(“E:\\temp\\std\\student.txt”,”r”)
f=open(r ‘D:\temp\file1.txt’,”r”)
Close() Function is used to close a File.
<file_object >.close()
eg:
myfile.close() , f.close()
➢ Modes:
Text File Binary File Description
‘r’ ‘rb’ read only
‘w’ ‘wb’ write only
‘a’ ‘ab’ append
‘r+’ ‘rb+’ read & write
‘w+’ ‘wb+’ write & read
‘a+’ ‘ab+’ append & read

Read File:
read(n), read() : Reads n bytes, Returns the read bytes in form
of a string. if no n specified, reads the entire file.
readline() : This method returns one line from the file.
readlines() : Reads all the lines and return them as each line a
string element in a list.
readlines(n) : Reads a line of the file and returns in form of a
string. For specified n, reads at most n bytes. However, does not reads
more than one line, even if n exceeds the length of the line
Write File:
write() : Insert a single line in the text file.
writelines() : Insert multiple lines in the text file.

file1.txt:
HELLO,
WELCOME TO
PYHON PRAGRAMMING&.
ITS AN OPENSOURCE LANGUAGE
ALSO ITS CALLED AS OBJECT OBRIENTED
PROGRAMMING,
HIGH LEVEL LANGUAGE.
INTERPRETER LANGUAGE.
Write a Program to Read the Contents in a File
f1=open(“Read.txt","r") Output:
print("Read All\n")
str=f1.read()
print("Read:",str)
f1.close()

m=open(“Read.txt","r")
print("Read N Bytes \n")
str2=m.read(10)
print("ReadBytes:",str2)
m.close()
Write a Program to Read the Contents in a File
mp=open("read.txt","r") Output:
print("ReadLine \n")
str3=mp.readline()
print("Readline Single:",str3,end=‘’)
mp.close()

mp=open("read.txt","r")
print("\n\nReadLine Multiple\n")
str3=mp.readline(25)
print("Readline Bytes:",str3,end='')
mp.close()
Program to Read the Contents in a File using “readlines”
mp=open(“Read.txt","r") Output:
print("ReadLines Bytes\n")
str3=mp.readlines(25)
print("ReadlineBytes:",str3,end='')
mp.close()

mm=open(“Read.txt","r")
print("ReadLines \n")
str4=mm.readlines()
print("ReadLines:",str4,end='')
mm.close()
Program to Write the Contents in a File using Write() & Writelines()
filewrite=open("student.txt","w+")
for i in range(5):
name=input("Enter the Student Name:")
filewrite.write(name)
filewrite.write("\n")
filewrite.close()
fr=open("student.txt","r+")
a=fr.read()
print(a)
fr.close()
Program to Write the Contents in a File using Write() & Writelines()

fwl=open("demo.txt","w+")
fwl.writelines(['Hello','\n','Welcome To','\n','Pyhon Pragramming'])
fwl.writelines('\n')
fwl.writelines(['Increditable','India', ‘\t’,'24'])
fwl.close()
Copy odd lines of one file to another file
f1=open("Oddeven.dat","r") Output
f2=open("Odd.dat","w")
cont= f1.readlines()
for i in range(0,len(cont)):
if (i%2!=0):
f2.write(cont[i]) Oddeven.dat
else:
pass
f1.close()
f2=open("Odd.dat","r")
conto=f2.read()
print(conto)
f2.close()
Copy the contents from one file to another file
def copy(file1,file2): Output:
f1=open(file1,"r")
f2=open(file2,"w")
for i in f1:
x=i.split('-')
if x[0]=='cricket’: #[‘cricket’,’abc’]
f2.write(i)
f1.close()
f2.close()
copy("sports.dat","cricket.dat")
Program to write and append data in text file
file1 = open("myfile.txt", "w")
L = ["This is Delhi \n", "This is Paris \n", "This is London"]
file1.writelines(L)
file1.close()
Output:
file1 = open("myfile.txt", "a")
file1.write("\n")
file1.write("Today")
file1.write("\n")
file1.write("Tomorrow")
file1.close()

file1 = open("myfile.txt", "r")


print("Output of Readlines after appending")
print(file1.read())
file1.close()
Program to write and append data in text file
zf=open("apd.txt","w+")
for i in range(3):
details= input("Enter the Fields Name:") Output:
zf.write(details)
zf.write("\n")
zf.close()
zf=open("apd.txt","a+")
zf.write(“Faxno")
zf.write("\n")
zf.write(“Phoneno")
zf.write("\n")
zf.close()
zf=open("apd.txt","r+")
p=zf.read()
print(p)
zf.close()
Write & Read Function in Binary File
import pickle
f1=open("Projj.dat","wb") Output:
d={'rno':100,'name':'hari','age':18}
pickle.dump(d,f1)
f1.close()

f1=open("Projj.dat","rb")
s=pickle.load(f1)
print(s)
f1.close()
Write in Binary File and Search a Record based on
‘rno’ from Binary File
import pickle
f1=open("Projj.bin","wb")
d={'rno':100,'name':'hari','age':18} Output1:
pickle.dump(d,f1)
f1=open("Projj.bin","rb")
s=pickle.load(f1)
print(s)
rn=int(input("Enter RollNo:"))
for R in s:
R=dict(s) Output2:
if R['rno']==rn: #100==18
print("Found:",R['name'])
break
else:
print("Not Found")
f1.close()
Write in Binary File and Search a Record based on
‘rno’ from Binary File
import pickle
f1=open("Projj.bin","wb")
d={'rno':100,'name':'hari','age':18} Output1:
pickle.dump(d,f1)
f1=open("Projj.bin","rb")
s=pickle.load(f1)
print(s)
rn=int(input("Enter RollNo:"))
R=dict(s) Output2:
if R['rno']==rn: #100==18
print("Found:",R['name'])
break
else:
print("Not Found")
f1.close()
1. Update a Field data in a Record of Binary File
import pickle
f1=open("Updateb.dat","wb+") Output1:
d={'jno':7,'name':'msd','age':37}
pickle.dump(d,f1)
f1=open("Updateb.dat","rb+")
s=pickle.load(f1)
print(s)
rn=int(input("Enter the JNo:"))
for R in s:
R=dict(s)
if R['jno']==rn: #7==7
print("Data Found:",R['name']) Output2:
R['name']=input("Enter the New Name:")
s['name']=R['name']
f1.seek(0)
pickle.dump(s,f1)
print("Name was Updated in Binary File")
break
else:
print("Record Not Found and Name not Updated")
f1=open("Updateb.dat","rb+")
nf=pickle.load(f1)
print(nf)
f1.close()
2. Update a Field data in a Record of Binary File
import pickle
f1=open("Updateb.dat","wb+") Output1:
d={'jno':7,'name':'msd','age':37}
pickle.dump(d,f1)
f1=open("Updateb.dat","rb+")
s=pickle.load(f1)
print(s)
rn=int(input("Enter the JNo:"))
R=dict(s)
if R['jno']==rn: #7==7
print("Data Found:",R['name']) Output2:
s['name']=input("Enter the New Name:")
pickle.dump(s,f1)
print("Name was Updated in Binary File")
break
else:
print("Record Not Found and Name not Updated")
f1=open("Updateb.dat","rb+")
nf=pickle.load(f1)
print(nf)
f1.close()
3. Update a Field data in a Record of Binary File
import pickle
f1=open("Updateb.dat","wb+") Output1:
d={'jno':7,'name':'[email protected]','age’:36}
pickle.dump(d,f1)
f1=open("Updateb.dat","rb+")
s=pickle.load(f1)
print(s)
rn=int(input("Enter the JNo:"))
R=dict(s)
if R['jno']==rn: #7==7
print("Data Found:",R['name']) Output2:
s['name']=input("Enter the New Name:")
f1.seek(0)
pickle.dump(s,f1)
print("Name was Updated in Binary File")
break
else:
print("Record Not Found and Name not Updated")
f1=open("Updateb.dat","rb+")
nf=pickle.load(f1)
print(nf)
f1.close()
Append Two Employee records like eno,ename,salary in a
Binary File and display records salary between x to y.
import pickle
fa=open("Employee.dat","wb")
rec=[]
for i in range(2):
Eno=int(input("Enter the Employee Number:"))
Ename=input("Enter the Employee Name:")
Salary=int(input("Enter the Employee Salary(Monthly):"))
data=[Eno,Ename,Salary] Output:
rec.append(data)
pickle.dump(rec,fa)
fa=open("Employee.dat","rb")
rl=pickle.load(fa)
for R in rl: #R=[07,‘msd’,29999]
Eno=R[0]
Ename=R[1]
Salary=R[2]
if Salary>=25000 and Salary<=30000:
print("ENo:",Eno,"EName:",Ename,"Salary:",Salary)
fa.close()
Write a Program by following the structure of each record in a “Product.dat”,
{‘Prodcode’:value,’ Prodname’:value, ‘Stock’:value}”.the values for prodcode
and name should be strings a stock is an integer.stock is updated based on prod
import pickle
p1=open("Product.dat","wb+")
rec={'Prodcode':'P101E9','Prodname':'xyz','Stock':10} Output 1:
pickle.dump(rec,p1)
p1=open("Product.dat","rb+")
s=pickle.load(p1)
print(s)
pc=input("Enter the Product Code:")
for R in s:
R=dict(s)
if R['Prodcode']==pc: # P101E9=P101E9
print("Product Found in the Name:",R['Prodname'])
s['Stock']=int(input("Enter the New Stock:"))
p1.seek(0) Output 2:
pickle.dump(s,p1)
print("Stock was Updated in Binary File")
break
else:
print("Record Not Found and Stock not Updated")
p1=open("Product.dat","rb+")
nf=pickle.load(p1)
print(nf)
p1.close()
Write a Program by following to dump multiple value to a binary file
import pickle
f=open("EmployData.bin", "wb")
empl={"Empno":1201,'Name':'Anushree','Age': 25,'Salary':47000}
emp2={"Empno":1211,'Name':'Zoya','Age': 30,'Salary':48000}
emp3={"Empno":1251,'Name':'Simarjeet','Age': 27,'Salary':49000}
emp4={"Empno":1266,'Name':'Alex','Age': 29,'Salary':50000}
data={1: empl, 2: emp2, 3: emp3, 4:emp4} Output:
pickle.dump(data, f)
print("File created successfully")
f=open("EmployData.bin", "rb")
content=pickle.load(f)
for i in content:
print (content[i])
f.close()
CSV (Comma Separated Values)
CSV File:
✓ CSV is a Simple file format used to store tabular data,
such as a Spreadsheet (or) Database.
✓ A CSV file stores tabular data in plain text.
✓ Each line of a file is a data record, each record
consists of one (or) more fields, separated by
commas.
✓ Commas is used as filed separated in the source of the
name for the file format.
✓ CSV file are very useful in E-Commerce Platforms.
Syntax:
import csv
Program to Read the Contents of “Records.csv”
import csv Output 1:
fo=open("Record.csv","r")
c=csv.reader(fo)
for row in c:
print(row)
fo.close()
Output 2:
import csv # [‘jno’,’name’,’age’]
fo=open("Record.csv","r")
c=csv.reader(fo)
columns=next(c)
#print(columns)
Record.csv
for row in c:
print(row)
fo.close()
Program to Read the Contents of “Records.csv”
import csv
fo=open("Record.csv","r") Output 1:
c=csv.reader(fo)
r1=next(c)
r2=next(c)
print("Next Value1 is: ",r1)
print("Next Value2 is: ",r2)
for row in c:
print(row) Record.csv
fo.close()
Write a program to Count the No.of Record in “NRecord.csv”
print the records in the form of comma separated values, instead of lists.

import csv Output:


fo=open("NRecord.csv","r")
c=csv.reader(fo)
columns=next(c)
Count=0
for row in c: NRecord.csv
Count=Count+1
print(','.join(row))
print('Number of Records inthe Fileis:',Count)
fo.close()
writerow() – used to write a single row in to the file.
writerows() – used to write ‘N’ no. of rows in to the file
without the help of loop (eg. For loop)
*****Write a program to “write” data into “marks.csv”*****
import csv
def MarksFun(Marks): #Marks=Marks.csv
Fields=["Name","Class","Percentage"]
Rows=[['Ram','XII','99'],['Rahul','XII','100'],['Ramesh','XII','95']]
fw=open(Marks,"w") Output:
c=csv.writer(fw,delimiter=',')
c.writerow(Fields)
c.writerows(Rows) Marks.CSV:
print(" The File 'Marks.CSV‘ is Created ")
fw.close()
MarksFun("Marks.csv")
Write a program to “write” data into “DeptData.csv”
import csv
def MarksFun(DeptData): # DeptData=DeptData.csv
Fields=["ID","Dept","Name"]
Rows=[['CSE101','CSE','Mahi'],['CSE102','CSE','Virat'],['IT103','IT','Rahul']]
fw=open(DeptData,"w") Output:

c=csv.writer(fw,delimiter='@')
c.writerow(Fields)
for i in Rows:
c.writerow(i) DeptData.CSV:
print(" The File 'DEPT.CSV‘ is Created ")
fw.close()
MarksFun("DeptData.csv")
Random Access Methods – seek() and tell()
Seek() - This method used to Change the Current Position of the
file handle to a given Specific Position.

Tell() –This Method gives the Current Position of the File Pointer.

Seek():
Seek(0) → sets the reference point at the beginning of
the file, which is default.
Seek(1) → sets the reference point at the current of
the file.(works only in binary file).
Seek(2) → sets the reference point at the end of
the file.(works only in binary file).
Seek() and Tell() in Text File
f=open("RandomAccessText.txt","r") #Output:
print("\n")
print(f.tell(),"\n")
f.read()
print(f.tell(),"\n")
f.seek(0)
print(f.tell(),"\n")
f.seek(10)
print(f.tell(),"\n")
f.read(19)
print(f.tell(),"\n")
f.seek(7)
print(f.tell(),"\n")
f.read(29)
print(f.tell(),"\n")
f.read(-1)
print(f.tell(),"\n")
f.seek(-1)
print(f.tell(),"\n")
f.close()
Seek() and Tell() in Binary File
f=open("randomaccess.dat","rb") Output:
print("\n")
print(f.tell(),"\n")
f.read()
print(f.tell(),"\n")
f.seek(10)
print(f.tell(),"\n")
f.read(5)
print(f.tell(),"\n")
f.seek(-5,2)
print(f.tell(),"\n")
f.read(3)
print(f.tell())
f.seek(-7)
print(f.tell())
f.close()
Seek() and Tell() in Text & Binary File
import pickle

f=open('seektellt.txt','w+') Output
f.write('Python\n')
f.write('Programming')
f.close()
f=open('seektellt.txt','r+')
print(f.tell())
print(f.read(7))
print(f.tell())
f.close()
print('\n')

fb=open('seektellb.dat','wb+')
d=['Python\n','Programming']
pickle.dump(d,fb)
fb.close()
fb=open('seektellb.dat','rb+')
print(fb.tell())
print(fb.read())
#print(fb.seek(5,1))
print(fb.tell())
fb.close()
Seek() and Tell() in Binary File

import pickle
fb=open('seektellbf4.dat','wb+')
d=['WelcometoPythonProgramming’]
pickle.dump(d,fb)
fb.close() Output
fb=open('seektellbf4.dat','rb+')
print(fb.tell(),"\n") 0
fb.read(10)
print(fb.tell(),"\n") 10
fb.seek(3)
print(fb.tell(),"\n") 3
fb.seek(2)
print(fb.tell(),"\n") 2
fb.seek(-10,2)
print(fb.tell(),"\n") 16
fb.seek(-5,1)
print(fb.tell(),"\n") 11
fb.seek(7,1)
print(fb.tell(),"\n") 18
fb.read(2)
print(fb.tell(),"\n") 20
fb.seek(0,1)
print(fb.tell(),"\n") 20
fb.seek(5,1)
print(fb.tell(),"\n") 25
fb.seek(0,2)
print(fb.tell(),"\n") 26
fb.read(3)
print(fb.tell(),"\n") 26
fb.seek(5)
print(fb.tell(),"\n") 5
fb.seek(5,2)
print(fb.tell(),"\n") 26
fb.seek(5,-5)
print(fb.tell(),"\n") Value Error
fb.seek(-5)
print(fb.tell()) OS Error : Invalid Statement
fb.close()
Standard Input, Output and Error Streams
➢ Keyboard, Monitor are the Standard input and output devices.
➢ These standard devices are implemented as files called standard
streams.
➢ Standard input device (stdin)->reads from the keyboard.
➢ Standard output device(stdout)->print to the display(monitor
screen).
➢ Standard error device(stderr)->same as stdout but only for error.
Syntax:
import sys #module
sys.stdin.read() #function
sys.stdout.write() #function
sys.stderr.write() #function
import sys Output:
print("Enter a Message:")
msgg=sys.stdin.read(10)
print("Your Message is:")
sys.stdout.write(msgg)
sys.stderr.write(" - END!")
print(“\n”)
fin=open("RandomAccessText.txt")
msg=fin.read()
sys.stdout.write(msg)
fin.close()
Using ‘with’ Statement perform write() and
read() Function
With Statement:

with open("Output.txt","w")as f: # f=open(“f.txt”,’’w”)


f.write("Hi Every One!")
with open("Output.txt","r")as f:
p=f.read()
print(p)
Output:
Using ‘with’ Statement perform dump() and
load() Function
With Statement:
import pickle
with open("Output.dat","wb")as f: # f=open("f.dat","wb")
a="Hi Every One!"
pickle.dump(a,f)
with open("Output.dat","rb")as f:
p=pickle.load(f)
print(p)
Output:
Using ‘with’ Statement perform reader() and
writer() Function
With Statement:
import csv
a=[['CSE101','CSE','Mahi'],['CSE102','CSE','Virat'],['IT103','IT','
Rahul']]
with open("Output.csv","w")as f: # f=open("f.csv","w")
b=csv.writer(f,delimiter='#')
b.writerows(a)
with open("Output.csv","r")as f: Output:
p=csv.reader(f)
for r in p:
print(r)
Absolute and Relative Paths
➢ Absolute path is defined as specifying the location of file
or directory from the root directory.
➢ Absolute path is a complete path from start of actual file
system from/directory.
(e.g.): E:\Python\Project\Railway\index.py

➢ The Relative path is defined as the path related to the


current working directly(cwd) denoted as a dot(.), while its
parent directory is denoted with two dots(..)

(e.g.): .\index.py #(.)is current working folder(Railway)

(e.g.): ..\index.py #(..)is current working folder(Railway)and


parent working folder(Project)
Flush Function

✓ When you write onto a file using any of the write functions,
Python holds everything to write in the file in buffer and pushes it
onto actual file on storage device a later time.

✓ If however, you want to force Python to write the contents of


buffer onto storage, you can use flush() function.

✓ Python automatically flushes the file buffers when closing


them i.e., this function is implicitly called by the close() function.
But you may want to flush the data before closing any file.

The syntax to use flush() function is:


<fileobject>.flush()
f = open('out.txt', 'w+')
f.write('The output is \n')
f.write( "My" + "work-status "+" is ")
f.flush()
s = 'OK.'
f.write(s) Output:
f.write('\n')
f.write('Finally Over\n')
f.flush()
f.close()
f = open('out.txt', 'r+')
r=f.read()
print(r)
f.close()
Exceptions and Exception Handling
Exception: Contradictory or Unexpected situation or unexpected
error, during program execution, is known as Exception.
During program development, there may be some cases where the
programmer does not have the certainty that this code-fragment is going to
work right, either because it accesses to resources that do not exist or
because it gets out of an unexpected range, etc.
These types of anomalous situations are generally called
exceptions and the way to handle them is called exception handling.
Broadly there are two types of errors :
(i) Compile-time errors. These are the errors resulting out of
violation of programming language’s grammar rules e.g., writing
syntactically incorrect statement like :
print ("A" + 2)
will result into compile-type error because of invalid syntax. All
syntax errors arereported during compilation.
(ii) Run-time errors. The errors that occur during runtime because of
unexpected situations.
Such errors are handled through exception handling routines of Python.
Exception handling is a transparent and nice way to handle program errors.

Many reasons support the use of exception handling. In other words,


advantages of exception handling are :
(i) Exception handling separates error-handling code from normal code.

(ii) It clarifies the code (by removing error-handling code from main line
of program) and enhances readability.

(iii) It stimulates consequences as the error-handling takes place at one


place and in one manner.

(iv) It makes for clear, robust, fault-tolerant programs.


So we can summarize Exception as :
It is an exceptional event that occurs during runtime and causes
normal program flow to be disrupted.
Some common examples of Exceptions are :
✓ Divide by zero errors
✓ Accessing the elements of an array beyond its range
✓ Invalid input
✓ Hard disk crash
✓ Opening a non-existent file
✓ Heap memory exhausted

Exception Handling:

✓ Way of handling anomalous situations in a program-run, is known as


Exception Handling.
When to Use Exception Handling
The exception handling is ideal for :
➢ Processing exceptional situations.
➢ Processing exceptions for components that cannot handle them directly.
➢ Large projects that require uniform error-processing.
Exception Handling in Python
✓ Exception Handling in Python involves the use of try and except clauses
in the following format
✓ wherein the code that may generate an exception is written in the try
block and the code for
✓ handling exception when the exception is raised, is written in except
block.
try :
#write here the code that may generate an exception
except :
#write code here about what to do when the exception has occurred
Example1:
try :
print ("result of 10/5 = ", (10/5))
print ("result of 10/0 = ", (10/0))
except :
print ("Divide by Zero Error! Denominator must not be zero!")
The output produced by above code is as shown below :

Example2:
try:
x = int("XII")
except:
print ("Error converting 'XII' to a number")
The output generated from above code is not the usual error now, it is :
E.1. Write a program to ensure that an integer is entered as input and in case
any other value is entered, it displays a message – ‘Not a valid integer’
ok = False
while not ok :
try :
numberString = input("Enter an integer:")
n = int(numberString)
ok = True
print(ok)
except :
print ("Error! Not a valid integer.")
Output:
E.2 Program to handle exception while opening a file.
try:
my_file = open("myfile.txt", "r")
print (my_file.read())
except:
print ("Error opening file")

The above program will open the file successfully if the file myfile.txt
exists and contains some data otherwise it shows an output as :

Now the above output may be of one of the two reasons :


(i) the file did not exist or (ii) there was no data in the file.
But the above code did not tell which caused the error.
Second Argument of the except Block:
You can also provide a second argument for the except block, which gives a
reference to the exception object. You can do it in following format :
try:
# code
except <ExceptionName> as <exArgument> :
# handle error here
The except clause can then use this additional argument to print the associated
error-message of this exception as : str (exArgument). Following code illustrates it
E.g.1
try:
print ("result of 10/5 = ", (10/5))
print ("result of 10/0 = ", (10/0))
except ZeroDivisionError as e :
print ("Exception - ", str(e))
The above code will give output as :
Handling Multiple Errors
Multiple types of errors may be captured and processed differently. It can
be useful to provide a more exact error message to the user than a simple “an error
has occurred.” In order to capture and process different type of exceptions, there
must be multiple exception blocks – each one pertaining to different type of
exception.
This is done as per following format :
try:
#:
except <exceptionName1> :
#:
except <exceptionName2> :
#:
except :
#:
else :
#If there is no exception then the statements in this block get executed.
E.3 Program to handle multiple exceptions.
try:
my_file=open("myfile.txt")
my_line=my_file.readline()
my_int=int(s.strip())
my_calculated_value=101/my_int
except IOError:
print("I/O error occurred")
except ValueError:
print("Could not convert data to an integer.") #Output:
except ZeroDivisionError:
print("Division by zero error")
except:
print("Unexpected error:")
else :
print("Hurray! No exceptions!")
The Finally Block:
You can also use a finally: block along with a try: block, just like
you use except: block, e.g., as :

try:
# statements that may raise exception
[except:
handle exception here]
finally:
# statements that will always run

The difference between an except: block and the finally: block is


that the finally: block is a place that contains any code that must execute,
whether the try: block raised an exception or not.
Program 1:

try:
fh = open("poem1.txt", "r")
print (fh.read())
except:
print ("Exception Occurred")
finally:
print ("Finally saying goodbye.")

Output:
Raising/Forcing an Exception
In Python, you can use the raise keyword to raise/force an
exception. That means, you as programmer can force an exception to occur
through raise keyword. It can also pass a custom message to your
exception handling module.
For example :
raise <exception> (<message>)
The exception raised in this way should be a pre-defined Built-in
exception. Consider following code snippet that forces a
ZeroDivisionError exception to occur without actually dividing a value by
zero :
import math
print ("Code to test wrong TYPE of arguments")
try:
num1 = int(input ("Enter the first number"))
result1 = math.sqrt(num1)
print ("Sqrt:", result1)
except ValueError:
print ("Please enter only Positive numbers")
try:
num2 = int(input("Enter the second number")) #Output:
result2 = math.pow(num1, num2)
print ("Pow:", result2)
except ValueError:
print ("Please enter only numbers")
finally:
print("Tested only wrong types; Wrong no. of requires requires *args")
THANK YOU

You might also like