gpt4 book ai didi

python - filehandle.tell() 函数的奇怪行为

转载 作者:行者123 更新时间:2023-11-28 23:03:48 26 4
gpt4 key购买 nike

我不明白为什么 tell() 函数在这种情况下不起作用。让我们创建一个包含字符串“1\n2\n3\n4\n”的文件:

f=open('test.tmp','w')
f.write('1\n2\n3\n4\n')
f.close()

现在,让我们打开它并运行以下代码:

fTellResults=[]
f=open('test.tmp','r+')
for line in f:
fTellResults.append(f.tell())
f.close()
print fTellResults

结果我得到:

[8L, 8L, 8L, 8L]

但是,我更希望这样:

[2L, 4L, 6L, 8L]

谁能解释一下为什么它会这样工作,我怎样才能得到预期的结果?

附注我在 Linux 上使用 Python 2.7.1

最佳答案

file.next()

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), 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.

基于此,我声明 file.tell 给出的位置是不正确的,因为该文件已被读取到预读缓冲区。

关于python - filehandle.tell() 函数的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8348798/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com