[Tutor] do I need f.close()

Alan Gauld alan.gauld at btinternet.com
Fri Jun 13 01:32:16 CEST 2008

"dave selby" <dave6502 at googlemail.com> wrote

> The whole topic came up because I just finished reading 'learning
> python' 3rd edition OReilly as a refresher where there are multiple
> instances of suggesting that you do the exact opposite eg ...

LP is a tutorial book so does not always teach industry strength
programming practice (in common with most tutorials!)

> [line.rstrip() for line in open('myfile')] ... p361
> for line in open('script1.py') ... p261& p276 where it is described 
> as
> 'best practice' for reading files line by line

Its the common idiom and for reading files not too bad.
I certainly use this sometimes but if its critical I will move
the open outside the loop:

f = open(...)
for line in f:....


[line.rstrip() for line in f]

But thats just so that I can detect and correct missing
files if necessary etc. Its not becauise of closure issues.
I'm fairly happy about letting the os close read only files,
its really for writing that you want to be explicit.

Alan G.

More information about the Tutor mailing list