FileNotFoundError: [Errno 2] 否 such file or directory
错误信息
[Errno 2] 否 such file or directory: 'missing.txt'
快速摘要
你 tried 到打开, 读取, or access file 那个 doesn't exist at specified path.
为什么发生
Typo in file name or path
file hasn't 是创建 yet
错误工作 directory — 相对 path doesn't resolve
Missing file extension
最小示例
✗ 错误代码
with open("missing.txt", "r") as f:
content = f.read() # FileNotFoundError✓ 修复代码
import os
if os.path.exists("data.txt"):
with open("data.txt", "r") as f:
content = f.read()
else:
print("File not found")
content = ""检查如果 file exists 使用 os.path.exists() 之前打开, or wrap in try/except FileNotFoundError.
如何诊断
检查 file path spelling and 情况 (情况-sensitive on Unix)
验证 file exists 使用 os.path.exists()
Print current 工作 directory 使用 os.getcwd()
如何修复
正确 file path or name
创建 file 之前打开它
Use 绝对 path 相反的 相对 path
Use try/except FileNotFoundError 到 handle missing files
如何预防
检查 os.path.exists() 之前打开
Use 上下文 managers (使用打开(...)) for file access
验证 file paths 从用户输入