在python遍历for循环中使用ftell()时出现意外的文件指针位置

2024-09-23 22:30:24 发布

您现在位置:Python中文网/ 问答频道 /正文

获取以下代码的意外输出:

sample.txt包含:

this is the first line
this is the second line
this is the third line
this is the fourth line
this is the fifth line
this is the sixth line

代码:

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  

我希望能显示文件指针在每行末尾的位置


Tags: ofthe代码txtislinethisfile
2条回答

tell()在文件对象上迭代时不起作用。 由于对更快的读取进行了一些优化,一旦开始迭代,文件中的实际当前药水就没有意义了。你知道吗

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()

我在文档中找到了相关部分:

A file object is its own iterator, for example iter(f) returns f (unless f is closed). When a file is used as an iterator, typically in a for loop (for example, for line in f: print line.strip()), the next() method is called repeatedly. This method returns the next input line, or raises StopIteration when EOF is hit when the file is open for reading (behavior is undefined when the file is open for writing). 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, combining next() with other file methods (like readline()) does not work right. However, using seek() to reposition the file to an absolute position will flush the read-ahead buffer.

相关问题 更多 >