reading file in for loop

Peter Otten __peter__ at web.de
Fri Sep 5 06:50:18 EDT 2014


loial 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

Whether the file is left open has nothing to do with how you leave the loop. 
The way you wrote it (readlines() reads all lines into a list and there is 
no reference to the file object left) CPython will close the file before you 
enter the loop:

$ python
Python 2.7.6 (default, Mar 22 2014, 22:59:56) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> for line in open("tmp.txt").readlines():
...     raw_input("you are here")
...     break
... 
you are here
[1]+  Angehalten              python
$ lsof *

Other implementations take a bit more time:

$ jython
"my" variable $jythonHome masks earlier declaration in same scope at 
/usr/bin/jython line 15.
Jython 2.5.3 (, Nov 21 2013, 23:15:42) 
[OpenJDK 64-Bit Server VM (Oracle Corporation)] on java1.7.0_65
Type "help", "copyright", "credits" or "license" for more information.
>>> for line in open("tmp.txt"): pass

... 
>>> 
[2]+  Angehalten              jython
$ lsof *
COMMAND  PID  USER   FD   TYPE DEVICE SIZE/OFF    NODE NAME
java    9396 xxxxx   34r   REG   8,23       17 5906455 tmp.txt
$ 





More information about the Python-list mailing list