开发者

Looping through a text file, readline() construction fails on large files

In Python 2.6 and 2.7 I would have thought that开发者_开发百科 these two constructs would be identical:

Method A

i=0
f=open('fred.txt','r')
for line in f.readline():
    i+=1
print i

Method B

i=0
f=open('fred.txt','r')
for line in f:
    i+=1
print i

However, when fred.txt grew to be 74,000 lines, with each line 2,684 characters in length, Method A prints 2685 while Method B prints 74000. Obviously, Method B is preferred, but why does Method A work for small files but fail for large files?


There’s a typo, it should be f.readlines(). You’re reading one line and looping through each character in the line.

Both methods (readlines vs iterating over the file directly) ought to give the same results, but readlines will store the entire contents in memory.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜