python 2.7搜索并替换文件中的多行

时间:2019-03-26 09:41:38

标签: python python-2.7

我有一个应该接收的python函数:

  • 文件路径
  • 具有要查找的旧值和要替换它的新值的元组列表。

假定该脚本生成使用元组值修改的相同文件(从旧到新)。到目前为止,这是我尝试过的:

def inplace_change(new_filename, old_string_new):
        for old_new in old_string_new:
            with open(new_filename, "rt") as fin:
                with open(new_filename, "wt") as fout:
                    for line in fin:
                        fout.write(line.replace(old_new[0], old_new[1]))

我通常将这样的元组列表传递给他们:

[('PidFile=/path/xxx.pid',
        'PidFile=/path/xxx.' + container_name + '.pid'),
       ('LogFile=/xx/log/nc_zabbix_agentd.log',
        'LogFile=/xx/log/yyyy.' + container_name + '.log')
    ...]

然后是文件所在的普通路径。

我设法很容易地仅替换一个元组(用新字符串替换单个旧字符串),但是当我拥有列表时,我无法获得完成此操作的逻辑。有任何想法吗?

2 个答案:

答案 0 :(得分:2)

罪魁祸首

for old_new in old_string_new:

应该是

for old_val, new_val in old_string_new:

更改此行

fout.write(line.replace(old_new[0], old_new[1]))

对此

fout.write(line.replace(old_val, new_val))

我已将您的问题最小化,以下内容应该非常容易理解:

old_string_new  = [ ('old1', 'new1'), ('old2', 'new2'), ('old3', 'new3')]

for old_val, new_val in old_string_new: 
    print(old_val, new_val)

输出

old1 new1
old2 new2
old3 new3

编辑

带有经过测试的代码的详细答案,假设我们有一个如下文件:

list.txt:

old1 hello there
okay old2 you will be replaced
haha bye bye old3

使用代码

import fileinput as fp

def inplace_change(filename, old_string_new):
    for old_val, new_val in old_string_new:
        with fp.FileInput(filename, inplace=True, backup='.bak') as file:
            for line in file:
                print(line.replace(old_val, new_val), end='')


old_string_new  = [('old1', 'new1'), ('old2', 'new2'), ('old3', 'new3')]
inplace_change('list.txt', old_string_new)

输出(list.txt)

new1 hello there
okay new2 you will be replaced
haha bye bye new3

答案 1 :(得分:1)

尝试这样的事情

import os

def replace_in_file(fn, replaces):
    with open(fn, 'r') as f1, open(fn+'.new', 'w') as f2:
        for line in f1.readlines():
            for a, b in replaces:
                line = line.replace(a, b)
            f2.write(line)
    os.rename(fn+'.new', fn)

replace_in_file('foo.txt', (('foo', 'bar'), ('hey', 'ho')))