How to safely open/close files in python 2.4 How to safely open/close files in python 2.4 python python

How to safely open/close files in python 2.4


See docs.python.org:

When you’re done with a file, call f.close() to close it and free up any system resources taken up by the open file. After calling f.close(), attempts to use the file object will automatically fail.

Hence use close() elegantly with try/finally:

f = open('file.txt', 'r')try:    # do stuff with ffinally:    f.close()

This ensures that even if # do stuff with f raises an exception, f will still be closed properly.

Note that open should appear outside of the try. If open itself raises an exception, the file wasn't opened and does not need to be closed. Also, if open raises an exception its result is not assigned to f and it is an error to call f.close().


In the above solution, repeated here:

f = open('file.txt', 'r')try:    # do stuff with ffinally:   f.close()

if something bad happens (you never know ...) after opening the file successfully and before the try, the file will not be closed, so a safer solution is:

f = Nonetry:    f = open('file.txt', 'r')    # do stuff with ffinally:    if f is not None:       f.close()


No need to close the file according to the docs if you use with:

It is good practice to use the with keyword when dealing with file objects. This has the advantage that the file is properly closed after its suite finishes, even if an exception is raised on the way. It is also much shorter than writing equivalent try-finally blocks:

>>> with open('workfile', 'r') as f:...     read_data = f.read()>>> f.closedTrue

More here: https://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects