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

Jeremy Leonard jrmy.lnrd at gmail.com
Thu Feb 18 13:02:56 EST 2016


On Tuesday, February 16, 2016 at 3:39:34 AM UTC-5, jf... 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...
> 
> but it didn't mention if the file will be closed automatically or not when the "for" block ends. Is there any document talking about this? and how to know if a file is in "open" or not?
> 
> --Jach Fong

One way of having a file automatically closed is to have something like:

with open("file_name") as foo:
    for x in foo:
       # process line x

Once the with block has completed, the file will be automatically closed. Sorry if this has already been posted, but I wasn't able to see it.



More information about the Python-list mailing list