如何用os.walk实现单文件查找并仅输出一次结果
问题描述
需要在指定根目录下递归搜索file.xml,要求:
- 找到文件时只输出一次
Found - 没找到时只输出一次
File does not exist - 根目录位置不固定,项目文件夹名称也不固定,没法指定具体路径
文件夹结构示例:
root folder/ ├─ Project Folder/ │ ├─ file.xml │ └─ other files/subfolders └─ ...
现有代码的问题:
- 初始代码会对每个非目标文件输出提示,不符合只输出一次的要求
- 修改后的代码能找到文件并输出,但找不到时不会给出提示
初始代码:
import os def check_file(x): #x = root folder dir for d in next(os.walk(x))[1]: #if I understand correctly, [1] will be Project Folder for root, directories, files in os.walk(x): for name in files: if "file.xml" not in name: print("found") else: print("File Missing")
修改后的代码:
import os def check_file(x): #x = root folder dir for d in next(os.walk(x))[1]: #if I understand correctly, [1] will be Project Folder for root, directories, files in os.walk(x): for name in files: if "file.xml" in name: print("found") else: pass
解决方案
方法一:用os.walk实现
核心是加个标记变量,遍历过程中找到文件就把标记设为True,遍历完根据标记输出结果,这样就能保证只输出一次。
另外注意:你之前的代码里next(os.walk(x))[1]是拿根目录下的子文件夹,但后面又直接os.walk(x)遍历整个根目录,这会重复遍历。下面分两种场景给出代码:
场景1:只从根目录下的子文件夹开始递归搜索
import os def check_file(root_dir): found = False # 获取根目录下的所有子文件夹 sub_folders = next(os.walk(root_dir))[1] for folder in sub_folders: folder_path = os.path.join(root_dir, folder) for root, _, files in os.walk(folder_path): if "file.xml" in files: found = True break # 找到就跳出内层循环,不用继续搜了 if found: break # 找到就跳出外层循环 print("Found" if found else "File does not exist")
场景2:整个根目录(包括根目录本身)递归搜索
import os def check_file(root_dir): found = False for root, _, files in os.walk(root_dir): if "file.xml" in files: found = True break # 找到就立即停止遍历 print("Found" if found else "File does not exist")
方法二:用pathlib(更简洁的现代写法)
Python 3.4+自带的pathlib模块操作文件系统更直观,代码也更简洁:
场景1:只从根目录下的子文件夹开始搜索
from pathlib import Path def check_file(root_dir): root_path = Path(root_dir) # 遍历根目录下的所有子文件夹,检查是否存在file.xml found = any((root_path / folder / "file.xml").exists() for folder in root_path.iterdir() if folder.is_dir()) print("Found" if found else "File does not exist")
场景2:整个根目录递归搜索
from pathlib import Path def check_file(root_dir): root_path = Path(root_dir) # 递归查找所有名为file.xml的文件 found = any(root_path.rglob("file.xml")) print("Found" if found else "File does not exist")
内容的提问来源于stack exchange,提问作者Avila
相关产品推荐
相关产品推荐

