use fileinput to read a specific line

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Tue Jan 8 14:12:13 CET 2008


On Mon, 07 Jan 2008 22:16:56 -0800, Russ P. wrote:

> One second thought, I wonder if the reference counting mechanism would
> be "smart" enough to automatically close the previous file on each
> iteration of the outer loop. If so, the files don't need to be
> explicitly closed.

Python guarantees[1] that files will be closed, but doesn't specify when 
they will be closed. I understand that Jython doesn't automatically close 
files until the program terminates, so even if you could rely on the ref 
counter to close the files in CPython, it won't be safe to do so in 
Jython. I don't know about IronPython or PyPy or the semi-mythical Parrot.

Given how little effort it is to explicitly close the files yourself, I 
don't see any reason to not close them, rather than relying on an 
implementation-dependent feature.



[1] Guarantee void under any circumstance that prevents files from being 
closed.

-- 
Steven



More information about the Python-list mailing list