[Tutor] do I need f.close()

Marilyn Davis marilyn at deliberate.com
Fri Jun 13 01:39:04 CEST 2008

On Thu, June 12, 2008 4:32 pm, Alan Gauld wrote:

> "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:....
> or
> [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, will the file close, even if it was opened for writing, when the
program ends?  I know it stays open if you're interactive, but otherwise

Marilyn Davis

> Alan G.
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

More information about the Tutor mailing list