John Machin wrote: > 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
Not to mention you can get bitten on the ass by a few characters sitting in a buffer someplace when you expect your file to have been fully written. Close the thing. Cheers, -T -- http://mail.python.org/mailman/listinfo/python-list