[Tutor] Closing files / strings are immutable
Danny Yoo
dyoo@hkn.eecs.berkeley.edu
Wed Mar 5 19:09:02 2003
> >3. Don't forget to close files (althoug I think Python might close it
> >for you, but still).
>
> In C-Python, this will not matter in the current implementation, since
> the file will be closed directly due to the reference counting garbage
> collection. In Jython, Java might well decide not to garbage collect
> yet, and then you try to open a file for writing which is already open
> for reading. Can you do that?
Hello!
When we have an open()ed file in "write" mode, it becomes more important
to make sure to close the file, especially in Jython. I don't know if
this is still true, but last time I checked, Jython suffered from a small
implementation problem: Java's buffered IO may not flush a file when the
file garbage collects, so it was very possible to lose changes to a file
by forgetting to close() the file explicitely. This is in Jython's FAQ:
http://www.jython.org/cgi-bin/faqw.py?req=show&file=faq03.008.htp
> >Almost-- Python strings are immutable, meaning that once the read()
> >method created the string it returned, that string object will never
> >change. So, even though the string object does indeed have a replace()
> >method, that method can't alter the string in place: instead, it
> >returns a new string with the changes.
> >
>
> Oops, we all forgot that, didn't we? It's easy to determine where a
> problem lies, and copy someone elses code without really checking it...
I did make the same careless mistake, too. Sorry, Ron. What was that old
saying... "Do what I say, and not what I do?" *grin*
Good luck!