[Tutor] closing files

Wesley Chun wesc@deirdre.org
Wed, 8 Aug 2001 17:17:39 -0700 (PDT)

On Mon, 30 Jul 2001, Danny Yoo wrote:
> On Mon, 30 Jul 2001 fleet@teachout.org wrote:
> > When opened files are not closed, what are the dangers?  Are files closed
> > by Python under some circumstances and, if so, which circumstances?
> When the variable goes out of scope, Python will automagically close() the
> file for us.  For example, your line:
> > open("writefile","w").write(open("readfile","r").read())
> is ok because Python transparently is doing the close()ing for us.
> (I'm being a little handwavy: it has more to do with the fact that the
> _reference count_ of the file goes to zero.)

as danny has indicated, Python's garbage collection mechanism
takes care of the files when they go out of scope.  however,
being from "the old school" and its dangers from C programming,
i recommend that you explicitly close your files... it's more
politically-correct, as far as i'm concerned.

in C (and other languages which do NOT clean up after your mess),
the dangers of not closing files does exist and is the greatest
when a file is open for write.  in such cases, data which has been
"written," i.e., sent from user-land to the kernel buffers awaiting
a real write to disk may not be flushed, causing your data to per-
haps *not* get written to the file or some similar inconsistency.

sure a one-liner is elegant, but have a close() in there will help
make the code functionality more succinct even if there's an extra
line or 2 of code.  the other thing is that if that body of code
does not go out of scope, the file remains open and an operating
system resource consumed until a close() occurs or the file handle
goes out of scope.

in applications which open lots of files, this is not a good idea
because you may run out of file descriptors and not be able to open
any more files until some of the already-opened ones are closed.

hope this helps!


- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Silicon Valley-SF Bay Area Python users group:  http://baypiggies.org

"Core Python Programming", Prentice Hall PTR, December 2000

wesley.j.chun :: wesc@baypiggies.org
cyberweb.consulting :: silicon.valley, ca