gpt4 book ai didi

python - 使用 Python 替换文件中的多行

转载 作者:太空宇宙 更新时间:2023-11-03 17:32:56 25 4
gpt4 key购买 nike

我有一个脚本,可以从一个文件中读取值并使用它们来更新另一个文件中的字段。如果我只进行一项更新,它会很好用,但如果我添加更多(注释行),它就会崩溃。

import re

def update_template():
with open("dest.txt", "r") as template:
lines = template.readlines()
with open("dest.txt", "w") as template:
for line in lines:
template.write(re.sub(field_one, one, line))
template.write(re.sub(field_two, two, line)) # <-- breaks here

with open('source.txt') as source:
for line in source:
one = "value1"
two = "value2"
field_one = "replace1"
field_two = "replace2"
update_template();

为每次更新调用该函数都有效,但我有很多数据,所以我不想这样做。有什么想法吗?

编辑:如果我在 dest.txt 中有以下内容:

replace1
replace2

运行后我最终得到:

value1
value1
value1
replace1
replace2
value2
value2
value2

那里应该只有“值”......

最佳答案

看起来您正在尝试将同一行写入文件两次,这可能会给您带来问题。尝试首先对 line 进行所有修改,然后写入文件:

with open("dest.txt", "w") as template:
for line in lines:
line = re.sub(field_one, one, line) # modify first
line = re.sub(field_two, two, line)
template.write(line) # write once after modifying

经过测试,它似乎可以在我的机器上运行。

关于python - 使用 Python 替换文件中的多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31619698/

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