gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:49:24 25 4
gpt4 key购买 nike

我正在尝试查找所有名为 logback.xml 的文件(在 Linux 系统上)并在其中替换一个字符串。这工作得很好(使用下面的脚本),但是,当它正在工作的目录中有超过 1 个文件时(即同时具有 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] Not a directory: '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,并且它将中断,因为该函数将立即调用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)

关于python - 使用Python在Linux上的许多文件中查找并替换字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26910983/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com