参考:
Python:获取当前目录下所有文件夹名称及文件夹下所有文件名称
Python:对当前目录下的多级文件夹中所有.txt文件追加写入相同内容
import os
def traverse_directories(directory, old_string, new_string):
# 遍历当前目录
for filename in os.listdir(directory):
file_path = os.path.join(directory, filename)
# 如果是文件夹,则递归处理其中的文件
if os.path.isdir(file_path):
traverse_directories(file_path, old_string, new_string)
# 如果是(文件名中含有"sub_string_name"的)文本文件,则追加文本内容
elif file_path.endswith(".txt"):
update_file(file_path, old_string, new_string)
def update_file(file_path, old_string, new_string):
with open(file_path, 'r', encoding='utf-8') as file:
file_data = file.read()
# 在文件中替换指定字符串
modified_data = file_data.replace(old_string, new_string)
with open(file_path, 'w', encoding='utf-8') as file:
file.write(modified_data)
print(file_path, "======Done!")
# 要替换的字符串和新字符串
old_string = """
xxxxxxx
xxxxxxx
xxxxxxx
"""
new_string = """
yyyyyyyyyyy
yyyyyyyyyyy
yyyyyyyyyyy
"""
# 获取当前位置
current_directory = os.getcwd()
# 调用函数开始处理
traverse_directories(current_directory, old_string, new_string)