如何使用python替换多个文件中的字符串

时间:2012-12-06 03:38:36

标签: python shell

我有两个文件(比如file1和file2)。 file1和file2中有字符串(等于字符串数)。 我想在包含xml文件的目录(包含多个子目录和xml文件)中搜索file1的内容,并将其替换为file2的内容。 any1可以帮助我使用脚本(紧急)吗?

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

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

1 个答案:

答案 0 :(得分: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()

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