I frequently see python code similar to
for line in open(filename):
do_something(line)
When does filename get closed with this code?
Would it be better to write
with open(filename) as f:
for line in f.readlines():
do_something(line)
filename
would be closed when it falls out of scope. That normally would be the end of the method.Yes, it's better to use
with
.Python Cookbook, Page 59.
Drop
.readlines()
. It is redundant and undesirable for large files (due to memory consumption). The variant with'with'
block always closes file.When file will be closed in the bare
'for'
-loop variant depends on Python implementation.python is garbage-collected - cpython has reference counting and a backup cycle detecting garbage collector.
File objects close their file handle when the are deleted/finalized.
Thus the file will be eventually closed, and in cpython will closed as soon as the for loop finishes.
The
with
part is better because it close the file afterwards. You don't even have to usereadlines()
.for line in file
is enough.I don't think the first one closes it.