Here is a super cautious, but correct way to open and read a file:
import sys
try:
file = open('myFile')
except IOError:
print 'File does not exist.'
sys.exit(1)
else:
print 'File exists.'
try:
lines = file.readlines()
finally:
file.close()
Following is the new, cleaner, but just as robust way to express the same operation in Python. This works because the file object was made to work with the new with keyword to ensure that the file is always closed after being opened. [1]
try:
with open('myFile') as file:
lines = file.readlines()
except IOError:
print 'File does not exist.'
sys.exit(1)
else:
print 'File exists and has been read.'
Footnotes
| [1] | The with statement is a newer feature in Python. It works with some objects to make the syntax of handling the object in a robust manner much cleaner. The with keyword also works with the socket object, which is of prime interest to us in this class. However, it was introduced after our text book was written. |