3 ms·
Without the context manager (with statement), the underlying file is closed when the file object is garbage-collected. In CPython, since reference counting is
by tjgq 13y ago
Without the context manager (with statement), the underlying file is closed when the file object is garbage-collected.
In CPython, since reference counting is used for GC, this occurs when the loop exits. However, other implementations (e.g. PyPy) may use different schemes that do not guarantee collection as soon as objects go out of scope. As an extreme, a valid and occasionally useful GC strategy is to never collect anything at all [0]!
Hence, if you want to portably ensure the file is closed, you should either use the context manager or call close() explicitly.
[0] http://blogs.msdn.com/b/oldnewthing/archive/2010/08/09/10047586.aspx http://blogs.msdn.com/b/oldnewthing/archive/2010/08/09/10047...