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

Posted

技术标签:

【中文标题】Python seek() 没有将指针移到正确的位置【英文标题】:Python seek() not shifting pointer to right place 【发布时间】:2021-09-15 21:36:14 【问题描述】:

我正在尝试以下 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 == 'b\n':
      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 == 'b\n':
      print("writing at position", fp)
      f.seek(fp)
      f.write("-")

能否帮助解释为什么前一种情况不起作用?谢谢!

【问题讨论】:

Does this help? 【参考方案1】:

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

在第二种情况下,在 readline() 之前,您正在调用 f.tell(),这实际上是将缓冲区刷新到磁盘。

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

【讨论】:

使用“rb+”也可以。但您需要更改字节类数组的字符串 感谢一百万!添加 flush() 有效。

以上是关于Python seek() 没有将指针移到正确的位置的主要内容,如果未能解决你的问题,请参考以下文章

Python3基础 file seek 将文件的指针恢复到初始位置

Python中的seek函数 指针 使用教程

25.Python:控制文件指针操作seek

文件二

Python 5月31日

python学习day10笔记