[Tutor] closing files

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Mon, 30 Jul 2001 13:59:48 -0700 (PDT)


On Mon, 30 Jul 2001 fleet@teachout.org wrote:

> In the discussion about the non-operating CGI form, I noticed that noone
> mentioned that the file opened for reading was never closed.  I recreated
> the situation in an interactive session (ie, opened a file for reading,
> then without closing it, opened it again for writing and wrote to it).
> Python didn't appear to care that the file opened for reading was not
> closed before the same file gets opened for writing.
> 
> 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.)

Hope this helps!