Open and closing files

John Machin sjmachin at lexicon.net
Thu Nov 30 22:15:54 EST 2006


Thomas Ploch wrote:
> Is it defined behaviour that all files get implicitly closed when not
> assigning them?
>
> Like:
>
> def writeFile(fName, foo):
> 	open(fName, 'w').write(process(foo))
>
> compared to:
>
>
> def writeFile(fName, foo):
> 	fileobj = open(fName, 'w')
> 	fileobj.write(process(foo))
> 	fileobj.close()
>
> Which one is the 'official' recommended way?

No such thing as an 'official' way.

Nothing happens until the file object is garbage-collected. GC is
generally not under your control.

Common sense suggests that
(a) when you are reading multiple files, you close each one explicitly
(b) when you are writing a file, you close it explicitly as soon as you
are done with it. That way you can trap any error condition and do
something moderately sensible -- better than getting an error condition
during GC when your Python process is shutting down.

HTH,
John




More information about the Python-list mailing list