[Tutor] closing files

fleet@teachout.org fleet@teachout.org
Mon, 30 Jul 2001 13:36:54 -0400 (EDT)


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?

If I write something like:

open("writefile","w").write(open("readfile","r").read())

are both the read and write files closed on execution of the command - or
should I spoil the beauty of a one-liner by adding:

readfile.close()
writefile.close()

					- fleet -