python - 使用 fileinput 替换文件中的多个字符串

标签 python python-3.x

我正在尝试替换文件中的多个字符串。

我的文件可能包含如下内容:

文件1:

#groovy
some test
some more test
REPLACE_1
REPLACE_OPTIONAL_1
REPLACE_2
end test

我正在尝试使用 fileinput 模块来替换上面的文本,但它没有按预期工作。我的方法是这样的:

    import fileinput
    def replace_method():
        file_path = './file1.txt'
        try:
            with fileinput.FileInput(file_path, inplace=True, backup=".bak") as file:
                for line in file:
                    print (line.replace('REPLACE_1', 'replaced_value1'), end='')
                    print (line.replace('REPLACE_OPTIONAL_1', 'replaced_value2'), end='')
                    print (line.replace('REPLACE_OPTIONAL_2', 'replaced_value3'), end='')
                   print (line.replace('REPLACE_2', 'replaced_value4'), end='')

        except Exception as e:
            print (str(e))

上面的代码有效,但它在新修改的文​​件中每行打印 4 次。我相信这与我可能错误使用的 line.replace 有关。

你能帮我解决这个问题吗? 如果您需要更多信息,请告诉我。

最佳答案

不要打印4次

import fileinput
def replace_method():
    file_path = './file1.txt'
    try:
        with fileinput.FileInput(file_path, inplace=True, backup=".bak") as file:
            for line in file:
                line = line.replace('REPLACE_1', 'replaced_value1')
                line = line.replace('REPLACE_OPTIONAL_1', 'replaced_value2')
                line = line.replace('REPLACE_OPTIONAL_2', 'replaced_value3')
                line = line.replace('REPLACE_2', 'replaced_value4')
                print (line, end='')
    except Exception as e:
        print (str(e))

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

相关文章:

python - Jinja2 {% include file %} 在搜索路径之外不起作用

python - 在 azure 函数中找不到本地模块

python - 如何在Python中以一定的速度在两个地理位置之间迭代(3)

python - 如何使用正则表达式从看似乱码的文本中提取某些子文本模式?

python - PyCharm 找不到库

python - 训练回归网络时的 NaN 损失

python - 在函数内导入 python 库与全局导入之间的区别?

python - 如何计算 python pandas 中的特定单元格值?

python - 替换 DataFrame 中时间戳的日期部分

python - 使用积分导出 CDF 的准确性