1

2つのファイルがあります(たとえば、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の入力ファイルがありません」というエラーが表示されます。

4

1 に答える 1

1

2 つのファイルを辞書に読み込む

ディレクトリをたどって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 に答える