Python替换文件中的多行

时间:2015-07-24 21:00:17

标签: python

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

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

应该只有&#39;值&#39;在那里...

1 个答案:

答案 0 :(得分:1)

看起来你试图将同一行写入文件两次,这可能会给你一个问题。首先尝试对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

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