本文目录导读:

- 使用
os.path.exists()(最常用) - 使用
os.path.isfile()(判断是否为文件) - 使用
pathlib(Python 3.4+ 推荐) - 使用
os.access()(检查访问权限) - 使用 try-except 捕获异常
- 完整示例对比
- 最佳实践建议
在Python中判断文件存在性有多种方法,以下是几种常见的实现方式:
使用 os.path.exists()(最常用)
import os
# 判断文件或目录是否存在
file_path = "test.txt"
if os.path.exists(file_path):
print(f"{file_path} 存在")
else:
print(f"{file_path} 不存在")
使用 os.path.isfile()(判断是否为文件)
import os
file_path = "test.txt"
if os.path.isfile(file_path):
print(f"{file_path} 是一个文件")
else:
print(f"{file_path} 不是文件或不存在")
使用 pathlib(Python 3.4+ 推荐)
from pathlib import Path
# Path.exists() - 判断路径是否存在
file_path = Path("test.txt")
if file_path.exists():
print(f"{file_path} 存在")
# Path.is_file() - 判断是否为文件
if file_path.is_file():
print(f"{file_path} 是一个文件")
使用 os.access()(检查访问权限)
import os
file_path = "test.txt"
if os.access(file_path, os.F_OK):
print(f"{file_path} 存在")
# 还可以检查其他权限
if os.access(file_path, os.R_OK): # 可读
print(f"{file_path} 可读")
if os.access(file_path, os.W_OK): # 可写
print(f"{file_path} 可写")
使用 try-except 捕获异常
file_path = "test.txt"
try:
with open(file_path, 'r') as file:
content = file.read()
except FileNotFoundError:
print(f"{file_path} 不存在")
except PermissionError:
print(f"没有权限访问 {file_path}")
完整示例对比
import os
from pathlib import Path
# 准备测试文件
test_file = "example.txt"
with open(test_file, 'w') as f:
f.write("Hello, World!")
# 测试目录
test_dir = "test_directory"
os.makedirs(test_dir, exist_ok=True)
# 1. os.path 方法
print("=== os.path 方法 ===")
print(f"文件存在: {os.path.exists(test_file)}") # True
print(f"是文件: {os.path.isfile(test_file)}") # True
print(f"目录存在: {os.path.exists(test_dir)}") # True
print(f"是目录: {os.path.isdir(test_dir)}") # True
# 2. pathlib 方法
print("\n=== pathlib 方法 ===")
p_file = Path(test_file)
p_dir = Path(test_dir)
print(f"文件存在: {p_file.exists()}") # True
print(f"是文件: {p_file.is_file()}") # True
print(f"目录存在: {p_dir.exists()}") # True
print(f"是目录: {p_dir.is_dir()}") # True
# 清理测试文件
os.remove(test_file)
os.rmdir(test_dir)
最佳实践建议
- Python 3.4+ 推荐使用
pathlib- 更面向对象,代码更清晰 - Python 2.x 或需要兼容旧版本 - 使用
os.path - 需要检查权限 - 使用
os.access() - 文件操作和存在检查一体 - 使用 try-except 模式
# 推荐用法
from pathlib import Path
config_file = Path("config.json")
if config_file.exists():
with open(config_file, 'r') as f:
data = f.read()
else:
print(f"配置文件 {config_file} 不存在")
# 创建默认配置
config_file.write_text('{"setting": "default"}')
这样处理既简洁又符合 Python 的最佳实践。