使用Python中的os
和fileinput
模块来实现这个任务。
- 此代码中使用
os.walk
来遍历指定目录下的所有文件和子目录。 - 代码仅处理以
.txt
或.py
结尾的文件,你可以根据需要调整这个条件。 - 替换操作是原地进行的,但是会生成一个带有
.bak
后缀的备份文件,以防发生意外。 - 请在使用此代码之前做好文件备份,以免不小心导致数据丢失。
import os import fileinput def replace_in_files(directory, search_str, replace_str): for root, dirs, files in os.walk(directory): for file in files: file_path = os.path.join(root, file) # 仅处理文本文件,你可能需要根据需要调整这个条件 if file.endswith('.txt') or file.endswith('.py'): with fileinput.FileInput(file_path, inplace=True, backup='.bak') as f: for line in f: print(line.replace(search_str, replace_str), end='') # 指定目录路径,将其中的 'path/to/your/directory' 替换为你的实际路径 directory_path = 'path/to/your/directory' search_string = 'a' replace_string = 'b' replace_in_files(directory_path, search_string, replace_string)