gpt4 book ai didi

python - 在特定位置更新文本文件中的字符串

转载 作者:行者123 更新时间:2023-11-28 16:48:38 25 4
gpt4 key购买 nike

我想找到一个更好的解决方案来实现以下三个步骤:

  1. 读取给定行的字符串
  2. 更新字符串
  3. 将更新后的字符串写回

下面是我的代码,但我想知道是否有更好(简单)的解决方案?

new='99999'

f=open('C:/Users/th/Dropbox/com/MS1Ctt-P-temp.INP','r+')
lines=f.readlines()
#the row number we want to update is given, so just load the content
x = lines[95]
print(x)
f.close()


#replace
f1=open('C:/Users/th/Dropbox/com/MS1Ctt-P-temp.INP')
con = f1.read()
print con
con1 = con.replace(x[2:8],new) #only certain columns in this row needs to be updated
print con1
f1.close()


#write
f2 = open('C:/Users/th/Dropbox/com/MS1Ctt-P-temp.INP', 'w')
f2.write(con1)
f2.close()

谢谢!更新:这次从 jtmoulia 得到一个想法变得更容易了

def replace_line(file_name, line_num, col_s, col_e, text):
lines = open(file_name, 'r').readlines()
temp=lines[line_num]
temp = temp.replace(temp[col_s:col_e],text)
lines[line_num]=temp
out = open(file_name, 'w')
out.writelines(lines)
out.close()

最佳答案

文本数据的问题,即使是表格化的,也是字节偏移量不可预测的。例如,当用字符串表示数字时,每个数字有一个字节,而当使用二进制(例如二进制补码)时,无论是小整数还是大整数,您总是需要四个或八个字节。

不过,如果您的文本格式足够严格,您可以通过替换字节而不改变文件大小来解决问题,您可以尝试使用 standard mmap module .有了它,您将能够将文件视为可变字节字符串并就地修改它的部分内容,然后让内核为您保存文件。

否则,任何其他答案都更适合该问题。

关于python - 在特定位置更新文本文件中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10711476/

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