No need to close file?

Robert Kern robert.kern at gmail.com
Tue Jul 18 17:17:50 EDT 2006


T wrote:
> Thomas Bartkus wrote:
>> "T" <ty.2006 at yahoo.com> wrote in message
>> news:1153252214.457508.269880 at 35g2000cwc.googlegroups.com...
>>> Do I need to close the file in this case?  Why or why not?
>>>
>>> for line in file('foo', 'r'):
>>>   print line
>> Are you asking if you can get away without closing it?
>> Or are you asking if it is a good idea to not close it?
>>
>> Good programming practice says that if you open it - you close it.
>>
>> And stay out of trouble ;-)
>> Thomas Bartkus
> 
> How do I close the file in the above case?

You rewrite the faulty code such that the above case isn't the above case anymore.

f = open('foo', 'r')
try:
   for line in f:
     print line
finally:
   f.close()

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco




More information about the Python-list mailing list