file.close()
with
statement. For example, the following code will
automatically close f when the with
block is exited::
from __future__ import with_statement # This isn't required in Python 2.6In older versions of Python, you would have needed to do this to get the same effect::
with open("hello.txt") as f:
for line in f:
print line
f = open("hello.txt")
try:
for line in f:
print line
finally:
f.close()
with
statement. If your code is intended to work with any file-like
object, you can use the function contextlib.closing instead of using
the object directly.