簡體   English   中英

如何使用Python替換多個文件中的字符串

[英]How to replace strings in multiple file using Python

我有兩個文件(例如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

但是我面臨的問題是這樣的。 該腳本搜索文件和字符串並打印(print(cmd)),但是當我將該腳本放置在目錄中時,我在CYGWIN窗口中看到此錯誤“沒有sed輸入文件”。

將兩個文件讀入字典

遍歷目錄以讀取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()

局限性在於,如果某些搜索字符串出現在替換字符串中,則該字符串可能會被替換多次。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM