will it cause any problems to open a read-only file & not close it?
Jeff Shannon
jeffshannon at gmail.com
Wed Mar 16 13:12:01 EST 2005
Tim Roberts wrote:
> Sara Khalatbari <sarapythonlist at yahoo.com> 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
More information about the Python-list
mailing list