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

时间:2014-11-13 14:19:14

标签: python linux

我正在尝试查找所有名为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并替换其中的条目。

有什么想法吗?

提前致谢。

1 个答案:

答案 0 :(得分:0)

处理目录时脚本的结构是:

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,它将会中断,因为该函数将立即调用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)