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

标签 python python-2.7

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

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  

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

最佳答案

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

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.

关于python - 在遍历for循环的python中使用ftell()的意外文件指针位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44870463/

相关文章:

python - 从 os x 中删除多个 python 安装

python - 根据日期值向月份列添加值

python - 从 python 脚本重现 Dymola 信息层

python - M2Crypto:覆盖主机名的连接后检查

python - Django / python : Change uploaded filename before saving file

python - Python 中在不同线程中调用相同函数的最佳方式是什么?

python - 获取一个参数

python - 缩小 PNG 图像会增加图像尺寸

python - 是否有重复重新分配变量的简写?

Python - 将 xml 中的特定行转换为小写并写回 - utf-8 问题