求助编写轻量Python 3.6.4脚本:在多级目录文件中搜索关键词
优化Python脚本实现多层目录关键词搜索
你的现有脚本只能遍历指定目录的第一层内容,没法处理嵌套的子文件夹,这也是为什么它没法替代Notepad++的目录搜索功能。我给你整理了两个实用的版本,分别对应搜索文件名/文件夹名和搜索文件内容的场景,完美适配Python 3.6.4版本:
一、搜索文件名/文件夹中的关键词(匹配路径名称)
这个版本会递归遍历目标目录下的所有层级,找出名称包含关键词的文件和文件夹,并输出完整路径,方便你快速定位:
import os def search_keyword_in_names(root_dir, keyword): # 遍历目标目录下的所有目录、子目录和文件 for dirpath, dirnames, filenames in os.walk(root_dir): # 检查文件夹名称 for dirname in dirnames: if keyword in dirname: full_dir_path = os.path.join(dirpath, dirname) print(f"📂 文件夹: {full_dir_path}") # 检查文件名称 for filename in filenames: if keyword in filename: full_file_path = os.path.join(dirpath, filename) print(f"📄 文件: {full_file_path}") if __name__ == "__main__": search_key = input("请输入要搜索的关键词: ") # 允许用户指定目标目录,默认用当前工作目录 target_directory = input("请输入目标目录(回车使用当前目录): ") or "." print(f"\n正在搜索目录 {target_directory} 中包含关键词 '{search_key}' 的内容...\n") search_keyword_in_names(target_directory, search_key)
二、搜索文件内容中的关键词(模拟Notepad++内容搜索)
如果你需要像Notepad++一样搜索文件内部的文本内容,可以用这个版本。它会自动跳过二进制文件避免报错,还会标注找到关键词的具体行号:
import os def search_keyword_in_content(root_dir, keyword): for dirpath, _, filenames in os.walk(root_dir): for filename in filenames: full_file_path = os.path.join(dirpath, filename) try: # 以UTF-8编码读取文件,遇到编码错误则判定为二进制文件 with open(full_file_path, 'r', encoding='utf-8') as file: # 逐行搜索,节省内存(适合处理大文件) for line_num, line_content in enumerate(file, start=1): if keyword in line_content: print(f"✅ 在文件 {full_file_path} 的第 {line_num} 行找到:") print(f" {line_content.strip()}\n") except UnicodeDecodeError: print(f"⚠️ 跳过二进制文件: {full_file_path}\n") except Exception as e: print(f"❌ 读取文件 {full_file_path} 时出错: {str(e)}\n") if __name__ == "__main__": search_key = input("请输入要搜索的关键词: ") target_directory = input("请输入目标目录(回车使用当前目录): ") or "." print(f"\n正在搜索目录 {target_directory} 中内容包含关键词 '{search_key}' 的文件...\n") search_keyword_in_content(target_directory, search_key)
效率与灵活性优化建议
- 添加文件类型过滤:比如只搜索
.py、.txt这类特定后缀的文件,只需在遍历文件名的循环里加判断if filename.endswith(('.py', '.txt')) - 超大量文件场景提速:用
concurrent.futures.ThreadPoolExecutor实现多线程并行读取文件,能显著提升搜索速度 - 保存结果到文件:把
print输出替换为写入文件,方便后续查阅。比如在脚本开头添加with open('search_result.txt', 'w', encoding='utf-8') as result_file:,然后用result_file.write(...)替代print语句
内容的提问来源于stack exchange,提问作者CYBORG




