【问题标题】:Python seek() not shifting pointer to right placePython seek() 没有将指针移到正确的位置
【发布时间】: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("-")

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

【问题讨论】:

标签: python readline seek tell


【解决方案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() 有效。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-11-13
  • 2018-07-25
  • 1970-01-01
  • 1970-01-01
  • 2011-06-12
  • 1970-01-01
  • 2016-07-21
相关资源
最近更新 更多