Thursday, April 7, 2011

Why doesn't Python release file handles after calling file.close() ?

I am on windows with Python 2.5. I have an open file for writing. I write some data. Call file close. When I try to delete the file from the folder using Windows Explorer, it errors, saying that a process still holds a handle to the file.

If I shutdown python, and try again, it succeeds.

From stackoverflow
  • It does close them. Are you sure f.close() is getting called? I just tested the same scenario and windows deletes the file for me.

  • Are you handling any exceptions around the file object? If so, make sure the error handling looks something like this:

    f = open("hello.txt")
    try:
        for line in f:
            print line
    finally:
        f.close()
    

    In considering why you should do this, consider the following lines of code:

    f = open('hello.txt')
    try:
        perform_an_operation_that_causes_f_to_raise_an_exception()
        f.close()
    except IOError:
        pass
    

    As you can see, f.close will never be called in the above code. The problem is that the above code will also cause f to not get garbage collected. The reason is that f will still be referenced in sys.traceback, in which case the only solution is to manually call close on f in a finally block or set sys.traceback to None (and I strongly recommend the former).

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.