[Tutor] Re: Closing files / strings are immutable

Magnus Lycka magnus@thinkware.se
Wed Mar 5 19:43:17 2003


At 16:08 2003-03-05 -0800, Danny Yoo wrote:
>When we have an open()ed file in "write" mode, it becomes more important
>to make sure to close the file, especially in Jython.

Yes, but is it always safe to implicitly close on read,
as in "data = file(filename).read()" if we subsequently
write to the same file? Or is there a risk that the
file is still open when we try to open it for writing,
and that the second open thus fail as in:

 >>> x = file('c:/autoexec.bat', 'r')
 >>> y = file('c:/autoexec.bat', 'w')
Traceback (most recent call last):
   File "<interactive input>", line 1, in ?
IOError: [Errno 13] Permission denied: 'c:/autoexec.bat'
 >>> x.close()

It shouldn't happen in CPython, since the file object
will be garbage collected at once if it's not bound to
any variable etc (like x above), but as I said, Java has
another type of garbage collector, and the file might
still be open when we try to open it the second time there.

This idiom ("d = file(fn).read()") is fairly common in
Python, but then most python code is not used in Jython,
and most of the time we don't write to the files we just
read.

As Danny also noted, it might be a good idea to save a
backup of the original. If you first rename the original,
then open it, and finally write your data to the file
name that the input file had before you renamed it, you
won't actually open the same file more then once, and
then it's not an issue, but it's no big effort to
explicitly type three lines:

f = file(fname, mode)
f.read() or f.write(x)
f.close()

For renaming (and deleting files) there are functions in
the os module (rename, remove). Never use stuff like
os.system("move %s %s" % (orgFileName, buFileName)) or
os.system("del %s" % filename) etc. The proper os module
calls will be portable and give proper exceptions on failure.
As always, reading the library module is a rewarding effort.


-- 
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/  mailto:magnus@thinkware.se