No need to close file?

Grant Edwards grante at visi.com
Tue Jul 18 17:01:01 EDT 2006


On 2006-07-18, Sybren Stuvel <sybrenUSE at YOURthirdtower.com.imagination> wrote:
> T enlightened us with:
>> Do I need to close the file in this case?  Why or why not?
>>
>> for line in file('foo', 'r'):
>>   print line
>
> Nope, it'll get closed automatically when the file object gets garbage
> collected.

Which might not happen until the program exits.  So, for small
programs, you don't have to close it.  Same as C or any other
language.

For large or longrunning programs that open lots of files, it's
generally recommended that you close files when you're done
with them.

-- 
Grant Edwards                   grante             Yow!  I am NOT a nut....
                                  at               
                               visi.com            



More information about the Python-list mailing list