Questions about file object and close()

Scott David Daniels Scott.Daniels at Acm.Org
Thu Dec 9 17:35:46 CET 2004

John Marshall wrote:
> On Thu, 2004-12-09 at 08:41 -0500, Peter Hansen wrote: 
>>John Marshall wrote:
>>>Does anyone see a problem with doing:
>>>    data = file("tata").read()
>>  ... a perfectly good explanation....
> It seems to me that a file.__del__() _should_
 > .... how he wishes it were designed ....
>Isn't that what __del__ (destructors) are supposed to handle
 > --cleaning up?

Just in case you are actually asking, and not simply complaining:

The existence of a __del__ method affects when a garbage collect
may remove an object (and may in some cases delay it).  In Jython
(and on top of any system doing its own garbage collection),
there may be no control over when an object is deallocated.
A close on an output file may finalize I/O that has been considered
a mistake, and it might cause an I/O error that will prevent the rest
of the program from executing.

>>One should use the open().read() idiom only in small
>>utility scripts and other such short-running applications.
> I don't see why this is so only for small scripts. As
> I question above, why doesn't the file object clean up
> after itself as a guaranteed course of action?

If you really want, define a function like:

     def contents(filename):
         source = open(filename)

and then you can make your small uses clear.

-Scott David Daniels
Scott.Daniels at Acm.Org

More information about the Python-list mailing list