[Python-Dev] lifting of prohibition against readlines inside a "for line in file" in Py3?

Mitchell L Model MLMLists at Comcast.net
Fri Feb 13 23:51:00 CET 2009


I discovered today that Python 2's prohibition against performing 
readlines on a file being iterated over appears to have been lifted 
in Python 3. Is this intentional? If it is, should it be added to the 
What's New in the documentation? I haven't been able to find anything 
mentioning the change.

	with open("lines.txt") as fil:
	    for line in fil:
	        print(line[:-1])
	        print(fil.readline())

produces a runtime error in 2.5 and 2.6 but not in 3.0 or 3.1 (and 
the output is as expected).

Also, I was surprised that nested "for line in file" that use the 
same file cause no problems in Python 2.5, 2.6, 3.0, or 3.1.

	with open("lines.txt") as fil:
	    for line1 in fil:
	        print(line1)
	        if line1[0] == '1':
	            for line2 in fil:
	                print(line2[:-1])
	                if line2[0] == '2':
	                    break
I would have expected the "for line in file" iterator to get confused 
by the file position having been moved out from under it, but I 
suppose all it has to do is just more readlines from wherever the 
file pointer is when it regains control. I mention this because apart 
from implementation considerations any reasoning that would 
discourage one from mixing line iterations with readlines might leave 
one thinking that nested line iterations wouldn't work either. But if 
it is intended that Python 3 allow mixing readlines with line 
iterations, there would be much less reason to suspect nested line 
iterations.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-dev/attachments/20090213/a6ca59f1/attachment-0001.htm>


More information about the Python-Dev mailing list