No need to close file?

Steve Holden steve at holdenweb.com
Wed Jul 19 04:01:35 EDT 2006


skip at pobox.com wrote:
>     T> Do I need to close the file in this case?  Why or why not?
> 
>     T> for line in file('foo', 'r'):
>     T>   print line
> 
> No.  The magic of reference counting.
> 
Though of course we have to remember that not all Python implementations 
*use* reference counting. It's certainly true, though, that most Python 
programmers are happy to rely on whatever garbage collector *is* 
implemented to detect the absence of references to the file and close it 
automatically. Or have the operating system do so if the interpreter 
somehow terminates without closing the file.

I suspect the real answer is "it isn't strictly necessary in modern 
environments, but it can never hurt".

regards
  Steve
-- 
Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd          http://www.holdenweb.com
Skype: holdenweb       http://holdenweb.blogspot.com
Recent Ramblings     http://del.icio.us/steve.holden




More information about the Python-list mailing list