Exception handling in Python - IOError

 # Exception handling - IOError

# Program to display contents of file


fs = None

try:

file_name=(input("Enter file name : ")).strip()

fs = open(file_name,"r")

except IOError as e:

print(e)

except:

print("Unknown error")

else:

while(True):

line = fs.readline()

if not line:

break

print(line,end="")

finally:

if(fs):

fs.close()


"""

input file: f1.txt

# File f1.txt


Welcome to python programming!!!

"""


"""

Sample output

>python EH.py

Enter file name : f1.txt

# File f1.txt


Welcome to python programming!!!


>python EH.py

Enter file name : f11.txt

[Errno 2] No such file or directory: 'f11.txt'


"""






No comments:

Post a Comment

Don't be a silent reader...
Leave your comments...

Anu