Python中如何通过文件名查找文件路径(含非项目目录场景)
在Python中通过文件名查找文件路径的方法
1. 搜索指定目录下的目标文件
如果知道文件大概所在的目录范围,用Python内置模块遍历查找是最稳妥的方式:
使用os.walk()(兼容所有Python版本)
遍历指定目录下的所有子目录,逐个匹配文件名:
import os def find_file(filename, search_root): for root, _, files in os.walk(search_root): if filename in files: # 返回第一个找到的文件的绝对路径 return os.path.abspath(os.path.join(root, filename)) # 未找到则返回None return None # 示例:搜索用户文档目录下的note.txt target_path = find_file("note.txt", "C:/Users/YourName/Documents") print(target_path)
如果需要收集所有同名文件,把return改成将路径添加到列表中即可。
使用pathlib.Path.rglob()(Python 3.4+ 推荐)
面向对象的文件路径操作方式,代码更简洁直观:
from pathlib import Path def find_file(filename, search_root): for match in Path(search_root).rglob(filename): return str(match.resolve()) return None # 示例:搜索D盘下的image.png target_path = find_file("image.png", "D:/") print(target_path)
2. 全系统范围查找文件
如果不知道文件所在目录,需要跨磁盘/全系统搜索,可采用以下两种方式:
扩展目录遍历范围
直接将搜索根目录设为系统根路径(Windows的C:/、D:/;Linux/macOS的/),但这种方式速度较慢,且可能遇到权限限制:
import os from pathlib import Path def find_file_global(filename): matches = [] if os.name == "nt": # 遍历Windows所有可用磁盘 drives = [f"{chr(c)}:/" for c in range(ord('A'), ord('Z')+1) if os.path.exists(f"{chr(c)}:/")] for drive in drives: for match in Path(drive).rglob(filename): matches.append(str(match.resolve())) else: # Linux/macOS搜索根目录 for match in Path("/").rglob(filename): matches.append(str(match.resolve())) return matches if matches else None # 示例:查找系统中所有的todo.txt all_paths = find_file_global("todo.txt") print(all_paths)
调用系统原生命令(速度更快)
利用系统自带的文件搜索命令(Windows的dir /s,Linux/macOS的find),通过subprocess调用:
import subprocess import platform def find_file_global(filename): if platform.system() == "Windows": # Windows下执行dir命令递归搜索,/b只返回路径 result = subprocess.run( ["dir", "/s", "/b", filename], capture_output=True, text=True, shell=True, encoding="gbk" # 适配Windows中文编码 ) if result.stdout: return result.stdout.strip().split("\n")[0] elif platform.system() in ["Linux", "Darwin"]: # Linux/macOS下执行find命令,只找文件 result = subprocess.run( ["find", "/", "-name", filename, "-type", "f"], capture_output=True, text=True ) if result.stdout: return result.stdout.strip().split("\n")[0] return None # 示例:全系统查找report.pdf target_path = find_file_global("report.pdf") print(target_path)
注意:系统命令方式依赖当前操作系统,Linux下搜索根目录可能需要
sudo权限,实际使用时需处理权限问题和编码兼容。
注意事项
- 同名文件:如果存在多个同名文件,上述方法默认返回第一个匹配项,若需收集所有结果,修改代码将路径存入列表即可。
- 性能:全系统搜索耗时较长,建议尽量缩小搜索范围以提升效率。
- 权限限制:部分系统目录或受保护文件夹可能无法访问,需在代码中添加
try-except块处理异常。
内容的提问来源于stack exchange,提问作者Khalid
相关产品推荐
相关产品推荐

