reading file in for loop

Chris Angelico rosuav at gmail.com
Fri Sep 5 12:31:02 CEST 2014


On Fri, Sep 5, 2014 at 8:20 PM, loial <jldunn2000 at gmail.com> wrote:
> If I read a file using a for loop, as follows, is the file left open if I execute a break in the for loop?
>
>
> for line in open(myFile).readlines():
>
>     if something:
>         break

It'll be closed when the object expires. With CPython, that's probably
going to happen fairly soon, but it's not guaranteed in any way. If
you want to be sure it's closed, use a 'with' statement - look it up
in the docs.

ChrisA



More information about the Python-list mailing list