有没有人碰巧知道为什么要以这种方式遍历文件:
输入:
f = open('test.txt', 'r')
for line in f:
print "f.tell(): ",f.tell()
输出:
f.tell(): 8192
f.tell(): 8192
f.tell(): 8192
f.tell(): 8192
我一直从 tell() 获取错误的文件索引,但是,如果我使用 readline,我会为 tell() 获取适当的索引:
输入:
f = open('test.txt', 'r')
while True:
line = f.readline()
if (line == ''):
break
print "f.tell(): ",f.tell()
输出:
f.tell(): 103
f.tell(): 107
f.tell(): 115
f.tell(): 124
顺便说一句,我正在运行 python 2.7.1。
最佳答案
将打开的文件用作迭代器使用预读缓冲区来提高效率。因此,当您遍历这些行时,文件指针会在文件中大步前进。
来自File Objects文档:
In order to make a for loop the most efficient way of looping over the lines of a file (a very common operation), the
next()
method uses a hidden read-ahead buffer. As a consequence of using a read-ahead buffer, combiningnext()
with other file methods (likereadline()
) does not work right. However, usingseek()
to reposition the file to an absolute position will flush the read-ahead buffer.
如果您需要依赖.tell()
,请不要将文件对象用作迭代器。您可以将 .readline()
改为迭代器(以牺牲一些性能为代价):
for line in iter(f.readline, ''):
print f.tell()
这使用了 iter()
function sentinel
参数将任何可调用对象转换为迭代器。
关于python - file.tell() 不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14341084/