Python脚本突发[WinError 3]路径找不到错误,重装Python仍未解决
问题原因与解决方法
核心问题
你遇到的[WinError 3]错误,根源是**os.listdir()只返回目标目录下的文件名,而非完整文件路径**。当你直接用这些文件名调用open()时,Python会在当前工作目录(不是你指定的Tables文件夹)中查找文件,自然找不到对应路径。
之前脚本能正常运行,大概率是因为当时你的Python程序工作目录恰好和Tables目录一致,后来工作目录变化(比如从其他文件夹启动脚本),就触发了错误——和Python版本无关,所以重装Python没用。
修复方案
方案1:用os.path.join拼接完整路径
修改代码,先保存目标目录的完整路径,再和文件名拼接成可直接使用的完整路径:
import os # 保存目标目录的完整路径 root_dir = r'C:\Users\Film\OneDrive\Documents\WORK\Blockfint\Richy_csv_files\Recovery_as_compu_11_14_2022_14_9_32\Tables' # 拼接文件名与根目录,得到完整路径 paths = [os.path.join(root_dir, filename) for filename in os.listdir(root_dir)] def files_with_word(word: str, paths: list) -> str: for path in paths: with open(path, "r") as f: if word in f.read(): yield path for filepath in files_with_word("Admin", paths): print(filepath)
方案2:用pathlib(更简洁的现代写法)
Python 3.4+推荐使用pathlib模块,处理路径更直观:
from pathlib import Path root_dir = Path(r'C:\Users\Film\OneDrive\Documents\WORK\Blockfint\Richy_csv_files\Recovery_as_compu_11_14_2022_14_9_32\Tables') def files_with_word(word: str, root_dir: Path): for file_path in root_dir.iterdir(): if file_path.is_file(): # 确保是文件而非子目录 with open(file_path, "r") as f: if word in f.read(): yield file_path for filepath in files_with_word("Admin", root_dir): print(filepath)
额外排查点
- 检查OneDrive同步状态:路径包含OneDrive,若文件被同步移除、路径变更(比如OneDrive文件夹重命名),也会导致找不到路径。
- 查看当前工作目录:可以在脚本开头加
print(os.getcwd()),确认当前工作目录是否和预期一致。
内容的提问来源于stack exchange,提问作者Tanatchat Laemkom Film
相关产品推荐
相关产品推荐

