首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用Python在linux上查找和替换许多文件中的字符串

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

Stack Overflow用户
提问于 2014-11-13 14:19:13
回答 1查看 66关注 0票数 0

我试图找到所有文件(在alinux系统上),这些文件名为logback.xml,并替换其中的一个字符串。但是,当它正在工作的目录中有多个文件时(即一个同时具有logback.xml和asdkjashdkja.xml的目录,它会给出一个错误,而在一个只有logback.xml的目录中,它没有),这是非常好的(下面的scrript )。下面是Python代码:

代码语言:javascript
复制
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并替换了其中的条目。

有什么想法吗?

提前谢谢。

EN

回答 1

Stack Overflow用户

发布于 2014-11-14 13:36:55

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

代码语言:javascript
复制
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)

您可以很容易地通过以下结构来修复这个问题:

代码语言:javascript
复制
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)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26910983

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档