python中使用ftell()遍历for循环时出现意外的文件指针位置
正在获取以下代码的意外输出:python中使用ftell()遍历for循环时出现意外的文件指针位置,python,python-2.7,Python,Python 2.7,正在获取以下代码的意外输出: sample.txt包含: 这是第一行 这是第二行 这是第三行 这是第四行 这是第五行 这是第六行 代码: import sys f1=open("sample3.txt",'r') print f1.tell() for line in f1: print line print "postion of the file pointer",f1.tell() 输出: 0 this is the first line
sample.txt
包含:
这是第一行这是第二行
这是第三行
这是第四行
这是第五行
这是第六行 代码:
import sys
f1=open("sample3.txt",'r')
print f1.tell()
for line in f1:
print line
print "postion of the file pointer",f1.tell()
输出:
0
this is the first line
postion of the file pointer 141
this is the second line
postion of the file pointer 141
this is the third line
postion of the file pointer 141
this is the fourth line
postion of the file pointer 141
this is the fifth line
postion of the file pointer 141
this is the sixth line
postion of the file pointer 141
我希望在迭代文件对象时,在每行末尾显示文件指针位置的内容不起作用。
由于对快速读取进行了一些优化,一旦开始迭代,文件中的实际当前药水就没有意义了
Python 3在这里提供了更多帮助:
OSError: telling position disabled by next() call
使用readline()
效果更好:
from __future__ import print_function
f1 = open('sample3.txt')
line = f1.readline()
while line:
print(line)
print("postion of the file pointer", f1.tell() )
line = f1.readline()
我在文档中找到了相关部分: 文件对象是它自己的迭代器,例如iter(f)返回f (除非f关闭)。当文件用作迭代器时,通常在 for循环(例如,对于f:print line.strip()中的行) 重复调用next()方法。此方法返回下一个输入 行,或在文件打开时命中EOF时引发StopIteration 用于读取(打开文件进行写入时,行为未定义)。 为了使for循环成为在 文件行(一种非常常见的操作),next()方法使用 隐藏预读缓冲区。由于使用了预读 buffer,将next()与其他文件方法(如readline()相结合) 不正常。但是,使用seek()将文件重新定位到 绝对位置将刷新预读缓冲区
感谢您的及时回复,可能是重复的。你能解释一下为什么我们不能用for循环迭代这个文件吗。