【问题标题】:How to replace strings in multiple file using Python如何使用 Python 替换多个文件中的字符串
【发布时间】:2023-03-28 09:14:01
【问题描述】:

我有两个文件(比如 file1 和 file2)。 file1 和 file2 中有字符串(字符串个数相等)。

我想在包含 XML 文件的目录(有多个子目录和 XML 文件)中搜索 file1 的内容,并将其替换为 file2 的内容。

import subprocess
import sys
import os
f_line = f.readlines()
g_line = g.readlines()
f=open("file1.txt")
g=open("file2.txt")

i = 0
for line in f_line:
    if line.replace("\r\n", "") != g_line[i].replace("\r\n", "") :
        print (line)
        print(g_line[i])
        cmd = "sed -i 's/" + line.replace("\r\n", "") + "/" + line[i].replace("\r\n","") + "/g' " + "`grep -l -R " + line.replace("\r\n", "") + " *.xml`"
        print(cmd)
        os.system(cmd)
    i = i + 1

但我面临的问题是这样的。该脚本搜索文件和字符串并打印(打印(cmd)),但是当我将此脚本放置在目录中时,我在 CYGWIN 窗口中看到此错误“没有用于 sed 的输入文件”。

【问题讨论】:

标签: python shell


【解决方案1】:

将两个文件读入字典

遍历目录读取xml文件,替换它们的内容,备份它们并覆盖原件

f1 = open('pathtofile1').readlines()
f2 = open('pathtofile2').readlines()
replaceWith = dict()
for i in range(len(f1)):
    replaceWith[f1[i].strip()] = f2[i].strip()

for root, dirnames, filenames in os.walk('pathtodir'):
    for f in filenames:
        f = open(os.path.join(root, f), 'r')
        contents = f.read()
        for k, v in replaceWith:
            contents = re.sub(k, v, contents)
        f.close()
        shutil.copyfile(os.path.join(root, f), os.path.join(root, f)+'.bak')
        f = open(os.path.join(root, f), 'w')
        f.write(contents)
        f.close()

一个限制是,如果某些搜索字符串出现在替换字符串中,一个字符串可能会被多次替换。

【讨论】:

    猜你喜欢
    • 2018-09-17
    • 2018-03-14
    • 1970-01-01
    • 1970-01-01
    • 2011-03-25
    • 2014-10-13
    • 2022-01-03
    • 2017-08-01
    • 2012-06-24
    相关资源
    最近更新 更多