[Tutor] do I need f.close()
Alan Gauld
alan.gauld at btinternet.com
Fri Jun 13 02:37:33 CEST 2008
"Marilyn Davis" <marilyn at deliberate.com> wrote
>> 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
> too?
It will if python closes cleanly. If the os, shell or python session
suffer any mishap then the file might not be closed and data may
be lost.
There are other dangers too with not closing writeable files.
If we have a long program we may inadvertantly reuse the
name and open a new file without having closed the old one.
That can result in unpredictable errors. In the worst case it
could lose/overwrite the entire original file. This can, in theory,
affect readable files too but it much less likely.
The best thing nowadays is to use the new with construct
since it guarantees file closure. Or in older versions always
wrap file handling code in a try/fuinally block with the closes
in the finally block.
Alan G.
More information about the Tutor
mailing list