微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

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

import random
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches


# generate some fake data of a similar range
x = np.random.random(100)*3000
y = np.random.random(100)*1

count_red = np.size(np.where(np.reshape(y,-1) >= .5))
count_blue = np.size(np.where(np.reshape(y,-1)< .5))

col = np.where(x<0,'k',np.where(y<.5,'b','r'))

fig,ax = plt.subplots(figsize =(10,7))

red_patch = mpatches.Patch(color='red',label=count_red)
blue_patch = mpatches.Patch(color='blue',label=count_blue)

dist_off_right_spline = .95
dist_from_top_spline  = .6

plt.title('Evolution of rapport of polarisation - Aluminium')
plt.xlabel('Time [min]')
plt.ylabel('Rapport [-]')
plt.tight_layout()
plt.savefig("Evolution of rapport of polarisation - (Aluminium).png")

plt.legend(bBox_to_anchor=(dist_off_right_spline,dist_from_top_spline),loc='upper left',handles=[red_patch,blue_patch])

plt.scatter(x,y,c=col,s=5,linewidth=1)
plt.show()
a
b
c
d
e
f

我原以为字母“c”会被覆盖为“-”,但我却像这样附加了破折号,尽管印刷品上写着“在位置 4 处书写”:

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("-")

当我交换 readline() 和 tell() 时输出是正确的(“b”将被“-”替换):

a
b
c
d
e
f-

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

解决方法

您需要将缓冲区 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() #------------->

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。