[Tutor] How to open the closed file again?

Kent Johnson kent37 at tds.net
Tue Jan 5 23:11:04 CET 2010


On Tue, Jan 5, 2010 at 4:06 PM, Luhmann <luhmann_br at yahoo.com> wrote:
>
> When there are no more references to an open file object, will it close, or the file will just remain open, forever unreachable?

When an open file object is garbage-collected it will be closed. In
current versions of CPython GC happens when there are no more
references to an object but other versions of Python (Jython,
IronPython) have different behaviour. There is no guarantee that an
object will ever be GDed.

My recommendation: for production code, explicitly close files. A
'with' block is the easiest way to do this. For quick-and-dirty code
running under CPython, don't worry about it. (Though I admit to being
paranoid enough to always explicitly close a file that is open for
writing.)

Kent


More information about the Tutor mailing list