[Tutor] closing files
fleet@teachout.org
fleet@teachout.org
Wed, 8 Aug 2001 22:31:53 -0400 (EDT)
On Wed, 8 Aug 2001, Wesley Chun wrote:
> 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.
> >
> 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.
Ok. Thanks. And for the explanation.
> 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.
Elegant? Well, I had "REALLY REALLY NIFTY" more in mind! :) I recently
revisited a couple of things I wrote like that, and I agree it's not
always easy to read. :( (However, just to satisfy my curiosity, could I
have tacked a '.close()' on there?)
> 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.
Yes, I see where that could become a problem.
> hope this helps!
Immensely! Thanks - and thanks for Core Python Programming. I'm studying
the "Sequences" chapter now.
- fleet -