Python seek()没有将指针移动到正确的位置



我正在尝试以下python seek((/tell((函数。"input.txt";是一个包含6个字母的文本文件,每行一个:

a
b
c
d
e
f
text = " " 
with open("input.txt", "r+") as f:   
while text!="":
text = f.readline()
fp = f.tell()
if text == 'bn':
print("writing at position", fp)
f.seek(fp)
f.write("-")

我正期待着这封信";c";被重写为"-"但相反,我得到了这样的破折号,尽管印刷品上写着";在位置4〃处书写:

a
b
c
d
e
f-

当我切换readline((和tell((时,输出是正确的("b"将被"-"代替(:

text = " "
with open("input.txt", "r+") as f:
while text!="":
fp = f.tell()           # these 2 lines
text = f.readline()     # are swopped
if text == 'bn':
print("writing at position", fp)
f.seek(fp)
f.write("-")

可以帮助解释为什么前一个案例不起作用吗?非常感谢。

您需要将缓冲区flush()发送到磁盘,因为write发生在内存中的缓冲区中,而不是磁盘上的实际文件中。

在第二个场景中,在readline()之前调用f.tell(),实际上是将缓冲区刷新到磁盘。

text = " " 
with open("input.txt", "r+") as f:   
while text!="":
text = f.readline()
fp = f.tell()
if text == 'bn':
print("writing at position", fp)
f.seek(fp)
f.write("-")
f.flush() #------------->

最新更新