Open operation exception handler
File open exception handler
#!/usr/bin/env python# ww w . j a va 2 s .c om
fname = 'abc.txt'
print
try:
fobj = open(fname, 'r')
except IOError, e:
print "*** file open error:", e
else:
for eachLine in fobj:
print eachLine,
fobj.close()
Handle file open exception inside a function.
import sys# from w w w . j a va 2s . c om
def open_file(file_name, mode):
"""Open a file."""
try:
the_file = open(file_name, mode)
except(IOError), e:
print "Unable to open the file", file_name, "Ending program.\n", e
raw_input("\n\nPress the enter key to exit.")
sys.exit()
else:
return the_file
trivia_file = open_file("trivia.txt", "r")
The code above generates the following result.