File Closing Problem in 2.3 and 2.4, Not in 2.5 (Final report)

Gabriel Genellina gagsl-py at yahoo.com.ar
Wed Jan 10 02:00:43 EST 2007


At Wednesday 10/1/2007 02:36, Julio Biason wrote:

>[Kinda stealing the thread]

(at least a related question!)

>If I use a file() in a for, how to I explicitely close the file?
>
><code>
>for line in file('contents'):
>    print line
></code>
>
>Would this work like the new 'with' statement or it will only be closed
>when the GC finds it?

Yes, the with statement is well suited for this:

with open('contents') as f:
   for line in f:
     print line

In earlier versions of Python you would write:

f = open('contents')
try:
   for line in f:
     print line
finally:
   f.close()


-- 
Gabriel Genellina
Softlab SRL 


	

	
		
__________________________________________________ 
Preguntá. Respondé. Descubrí. 
Todo lo que querías saber, y lo que ni imaginabas, 
está en Yahoo! Respuestas (Beta). 
¡Probalo ya! 
http://www.yahoo.com.ar/respuestas 




More information about the Python-list mailing list