Is close() necessary when using iterator on a Python file object [duplicate]

Close is always necessary when dealing with files, it is not a good idea to leave open file handles all over the place. They will eventually be closed when the file object is garbage collected but you do not know when that will be and in the mean time you will be wasting system resources by holding to file handles you no longer need.

If you are using Python 2.5 and higher the close() can be called for you automatically using the with statement:

from __future__ import with_statement # Only needed in Python 2.5
with open("hello.txt") as f:
    for line in f:
        print line

This is has the same effect as the code you have:

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

The with statement is direct language support for the Resource Acquisition Is Initialization idiom commonly used in C++. It allows the safe use and clean up of all sorts of resources, for example it can be used to always ensure that database connections are closed or locks are always released like below.

mylock = threading.Lock()
with mylock:
    pass # do some thread safe stuff

Leave a Comment