Will file be closed automatically in a "for ... in open..." statement?

Terry Reedy tjreedy at udel.edu
Tue Feb 16 04:41:56 EST 2016

On 2/16/2016 3:39 AM, jfong at ms4.hinet.net wrote:
> I know
>      with open('foo.txt') as f:
>          ...do something...
> will close the file automatically when the "with" block ends.
> I also saw codes in a book:
>      for line in open('foo.txt'):
> 	...do something...

Some books were originally written before 'with context_manager' was 
added, or a little later, before it became the normal thing to do.

Terry Jan Reedy

More information about the Python-list mailing list