I am trying to catch error on file input/output. The try functions works fine but as it pass to the next line my code breaks. How can I exit gracefully when the 'infile' doesnt exist?
try:
infile = open ('Book1.txt', "r")
except IOError:
print "input file %s is missing" %'Book1.txt'
tex1 = infile.readline()
outfile = open ('Book11.txt', "w")
while tex1:
rfields = tex1.split()
# do something
print >> outfile, 'something'
outfile.close()
infile.close()
the error message I got:
input file Book1.txt is missing
Traceback (most recent call last):
File "D:\pythonLearing\trial.py", line 11, in <module>
tex1 = infile.readline()
NameError: name 'infile' is not defined
Thank you in advance.