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

Viewed 60843

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.

8 Answers
Related