本文目录导读:

我来介绍几种在Python中删除文件的方法:
使用 os.remove() 方法
import os
# 删除单个文件
file_path = "example.txt"
try:
os.remove(file_path)
print(f"文件 {file_path} 删除成功")
except FileNotFoundError:
print(f"文件 {file_path} 不存在")
except PermissionError:
print(f"没有权限删除文件 {file_path}")
使用 os.unlink() 方法
import os
# os.unlink() 和 os.remove() 功能相同
file_path = "test.txt"
try:
os.unlink(file_path)
print("文件删除成功")
except Exception as e:
print(f"删除失败: {e}")
使用 pathlib 模块 (Python 3.4+)
from pathlib import Path
# 使用 Path.unlink() 方法
file_path = Path("document.txt")
try:
file_path.unlink()
print("文件删除成功")
except FileNotFoundError:
print("文件不存在")
except PermissionError:
print("没有权限删除")
完整示例:检查并删除文件
import os
from pathlib import Path
def delete_file_safe(file_path):
"""
安全删除文件,增加各种检查
"""
# 方法1:使用 os.path.exists()
if os.path.exists(file_path):
try:
os.remove(file_path)
print(f"文件 {file_path} 已成功删除")
return True
except Exception as e:
print(f"删除文件失败: {e}")
return False
else:
print(f"文件 {file_path} 不存在")
return False
def delete_file_with_pathlib(file_path):
"""
使用 pathlib 安全删除文件
"""
path = Path(file_path)
if path.exists():
try:
path.unlink()
print(f"文件 {file_path} 已成功删除")
return True
except Exception as e:
print(f"删除文件失败: {e}")
return False
else:
print(f"文件 {file_path} 不存在")
return False
# 使用示例
if __name__ == "__main__":
# 测试文件删除
delete_file_safe("test.txt")
delete_file_with_pathlib("document.txt")
批量删除文件
import os
import glob
from pathlib import Path
# 方法1:使用 glob 删除多个文件
def delete_multiple_files(pattern):
"""删除匹配模式的所有文件"""
file_list = glob.glob(pattern)
for file_path in file_list:
try:
os.remove(file_path)
print(f"已删除: {file_path}")
except Exception as e:
print(f"删除 {file_path} 失败: {e}")
# 方法2:使用 pathlib
def delete_files_in_directory(directory, extention=".txt"):
"""删除指定目录下所有特定扩展名的文件"""
for file_path in Path(directory).glob(f"*{extention}"):
try:
file_path.unlink()
print(f"已删除: {file_path}")
except Exception as e:
print(f"删除失败: {e}")
# 使用示例
delete_multiple_files("*.txt")
delete_files_in_directory("./temp", ".log")
注意事项
import os
# 检查文件是否可写
def check_and_delete(file_path):
if os.access(file_path, os.W_OK):
# 检查是否有写入权限(包括删除权限)
os.remove(file_path)
print("文件已删除")
else:
print("没有权限删除此文件")
# 删除前确认
response = input(f"确定要删除文件吗?(y/n): ")
if response.lower() == 'y':
delete_file_safe("important.txt")
else:
print("操作取消")
常见错误处理
import os
import errno
def robust_delete(file_path):
"""健壮的文件删除函数"""
try:
os.remove(file_path)
except OSError as e:
if e.errno == errno.ENOENT:
print("文件不存在")
elif e.errno == errno.EACCES:
print("权限不足")
elif e.errno == errno.EISDIR:
print("路径是目录,不能使用remove删除")
else:
print(f"其他错误: {e.strerror}")
except Exception as e:
print(f"意外错误: {e}")
推荐使用
对于现代Python开发,推荐使用 pathlib 模块,因为它更加面向对象和易用:
from pathlib import Path
# 推荐的删除方式
path = Path("file.txt")
if path.exists():
path.unlink(missing_ok=True) # Python 3.8+ 支持 missing_ok 参数
选择哪种方法取决于你的具体需求和个人偏好,但记住始终添加适当的异常处理。