1

我有两个文件(比如 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 的输入文件”。

4

1 回答 1

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()

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

于 2012-12-06T03:57:31.267 回答