Tim Roberts wrote:
Sara Khalatbari <[EMAIL PROTECTED]> wrote:


Dear friends
In a code, I'm opening a file to read. Like :
  lines = open(filename).readlines()
& I'm never closing it.
I'm not writing in that file, I just read it.

Will it cause any problems if you open a file to read
& never close it?

A file is closed when the last reference to it is deleted. Since you never save a reference to this file, the last reference is deleted as soon as the readlines() call finishes.

So, the file will be closed when you move to the next statement.

This is true in current versions of CPython, but is not necessarily true in all implementations of Python. In particular, Jython uses Java's garbage collector; an object becomes available for collection when the last reference is deleted, but that collection may not (probably won't) happen right away. Since the automatic file closing happens as part of the object deletion, files opened in this way won't be closed until the garbage collector runs (and collects this file object).


Most of the time, this won't be a problem, but it's good to be aware that things are not necessarily as cut-and-dried as they might seem.

Jeff Shannon

--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to