will it cause any problems to open a read-only file & not close it?

Jeff Shannon jeffshannon at gmail.com
Mon Mar 14 19:45:08 EST 2005


Daniel Dittmar wrote:

> Fuzzyman wrote:
> 
>> Sara Khalatbari wrote:
>>
>>> Will it cause any problems if you open a file to read
>>> & never close it?
>>
>>
>> Under CPython the filehandle will be automatically garbage collected.
>> Under JPython (Jython) it won't be... 
> 
> 
> Isn't it rather that CPython will close the file as soon as the last 
> reference is dropped, which is probably right after the read returns?
> 
> Whereas Jython/Java will close the file, when the garbage collector 
> actually reclaims the object, which will be later. Or much later.

That's my understanding.  In either case, it will only cause 
"problems" if you're doing something else with that file immediately 
afterwards.  In the case of files that you're writing, this includes 
reading the file from another program -- a file that hasn't been 
closed probably also hasn't been flushed to disk, and therefore (IIUC) 
the file is not reliably readable until the Jython/Java program has 
terminated (or GC can otherwise be guaranteed to have run).

However, in the case where you're simply reading the contents of a 
file and don't need to do anything else with the disk file or file 
object after that, then this idiom should be harmless even under Jython.

Jeff Shannon




More information about the Python-list mailing list