tags:

views:

94

answers:

2

I'm currently writing a small script for use on one of our servers using Python. The server only has Python 2.4.4 installed.

I didn't start using Python until 2.5 was out, so I'm used to the form:

with open('file.txt', 'r') as f:
    # do stuff with f

However, there is no with statement before 2.5, and I'm having trouble finding examples about the proper way to clean up a file object manually.

What's the best practice for disposing of file objects safely when using old versions of python?

A: 

Just use:

f = open('file.txt', 'r')

# do something

f.close()
Uku Loskit
And if `# do something` raises an exception?
Jon-Eric
Mostly likely the OS will close any files left open by the process, or the Python interpreter will if it is still running when the unhandled exception occurs.
martineau
+14  A: 

Use try/finally:

f = open('file.txt', 'r')

try:
    # do stuff with f
finally:
    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().

Jon-Eric
Very simple, thanks. For some reason I was expecting that I'd need something more involved.
TM
If `open` fails, an exception will be raised before the `try/finally` block is even entered. So `close` will not be called. (That's why you should call `open` before the `try`.)
FogleBird
@TM I added a note about `open` raising an exception.
Jon-Eric
This is what the with statement translates to behind the scenes.
Arlaharen
@Jon-Eric thanks, I realize my question didn't really make sense, as open would still do the same thing if it couldn't open the file as the `with` statement.
TM