簡體   English   中英

使用Python在Linux上的許多文件中查找和替換字符串

[英]Finding and replacing a string in many files on linux with Python

我正在嘗試查找所有名為logback.xml的文件(在alinux系統上),並在其中替換一個字符串。 這樣做非常好(使用下面的scrript),但是,當它正在使用的目錄中有多個文件時(即同時具有logback.xml和asdkjashdkja.xml的目錄,它將給出錯誤,並且該目錄只有logback.xml而沒有)。 這是下面的Python代碼:

def replace_loglevel(file_to_edit, source_text, replace_text):
    """ Open file and replace the source_text with the replace_text strings """
    open_file = open(file_to_edit, 'r')
    text_from_original = open_file.read()
    open_file.close()

    file_to_write = open(file_to_edit, 'w')
    file_to_write.write(text_from_original.replace(source_text, replace_text))
    print "Replacing string %s with string %s in file %s" % (source_text, replace_text, file_to_edit)

def backup_and_edit_files(dir_path, backup_dir):
    """ Backup the file and replace the source_text with replace_text """
    for item in os.listdir(dir_path): # Iterate over each dir in the dir_path
        path = os.path.join(dir_path, item) # Create full path to file
        if path not in processed_files:
            if os.path.isfile(path) and item == file_to_edit: # Match filename to be the same as in file_to_edit
                print "Matched file %s " % (file_to_edit)
                print "Backing up the current file - %s - before editing" % (item)
                backup_file(path, backup_dir)
                print "Replacing loglevel from %s to %s " % (source_text, replace_text)
                replace_loglevel(path, source_text, replace_text)
                processed_files.append(path)
                print "Processed - %s" % path
            else:
                backup_and_edit_files(path, backup_dir)

當同一目錄中有更多文件時,我得到的錯誤是:

OSError:[Errno 20]不是目錄:'path / to / file / fgfd.xml'

當我從目錄中刪除此fgfd.xml時,腳本運行良好,並找到logback.xml並替換了其中的條目。

有任何想法嗎 ?

提前致謝。

處理目錄時腳本的結構為:

if os.path.isfile(path) and item == file_to_edit: # Match filename to be the same as in file_to_edit
    ... process logback.xml
else:
    backup_and_edit_files(path, backup_dir)

因此,如果該目錄包含另一個文件backup_and_edit在該文件上調用backup_and_edit ,因為該函數將立即調用os.listdir(path) ,所以它將中斷。

您可以使用以下結構輕松修復該問題:

if os.path.isfile(path) and item == file_to_edit: # Match filename to be the same as in file_to_edit
    ... process logback.xml
elif os.path.isdir(path): # only descend into directories
    backup_and_edit_files(path, backup_dir)

暫無
暫無

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

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