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

file, iterator, python

Solution

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

Problem

Is it bad practice to do the following and not explicitly handle a file object and call its `close()` method? ``` for line in open('hello.txt'): print line ``` NB - this is for versions of Python that do not yet have the `with` statement. I ask as the Python documentation seems to recommend this :- ``` f = open("hello.txt") try: for line in f: print line finally: f.close() ``` Which seems more verbose than necessary.

Original source

Related problems