tags:

views:

92

answers:

2

If I do the following, does filehandle get closed automatically as it goes out of scope in Python:

def read_contents(file_path):
  return file(file_path).read()

If it doesn't, how can I write this function to close the scope automatically?

+11  A: 

It should close the file handle in the file's __del__ statement, but a better approach would be to use a with block:

def read_contents(file_path):
  with open(file_path, 'r') as f:
    return f.read()

See http://docs.python.org/library/stdtypes.html#file.close for more information.

FogleBird
Just to mention: file returns a file object which has a close method. That would be the most straight forward solution, but "with" is obviously the nicer one.
Achim
I have a problem -- I don't have `with` in my Python. Is it ok to import from future? I have Python 2.5.
bodacydo
If you have Python 2.5, then yes.
Tim Pietzcker
Thanks. One more question - if I transfer my app to installation with Python 2.6, will `import with from future` still work?
bodacydo
That or use the try/finally approach as described in the link.
FogleBird
Yes, it will still work in 2.6
FogleBird
Thanks! (15 char limit)
bodacydo
+5  A: 

To expand on FogleBird's answer, if you do not explicitly close it then the file will be closed automatically when the file object is destroyed. In CPython this will happen as soon as there are no more references to it, e.g. if it is a local variable in a function and the function ends. However if an exception is thrown in the function and file is not explicitly closed using a with statement or a try:...finally: then a reference to the file will be kept as part of the stack trace in the traceback object and the file will not be closed, at least until the next exception is thrown.

Also IronPython and Jython use the garbage collection facilities of the .Net CLR and Java JVM respectively. These are not reference counted, so the file will remain open indefinitely until the garbage collector decides to reclaim the object's memory or the program terminates.

So in general it is important to explicitly close the file using either with: or try:...finally:.

Of course all this is holds true for any other type of object that requires explicit cleanup.

Dave Kirby
+1, all good points that I didn't bother to mention. :)
FogleBird
"didn't bother" - i didn't know any of this. :(
bodacydo
Thanks for mentioning all these important points!
bodacydo