本文目录导读:

在Python中删除指定文件,最常用的方法是使用 os.remove() 或 pathlib.Path.unlink(),以下是几种常见情况的操作方法:
使用 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}'")
except Exception as e:
print(f"删除文件时发生错误: {e}")
使用 pathlib 模块(Python 3.4+ 推荐)
from pathlib import Path
file_path = Path("example.txt")
try:
file_path.unlink()
print(f"文件 '{file_path}' 已成功删除")
except FileNotFoundError:
print(f"文件 '{file_path}' 不存在")
except PermissionError:
print(f"没有权限删除文件 '{file_path}'")
删除前检查文件是否存在
import os
file_path = "example.txt"
if os.path.exists(file_path):
try:
os.remove(file_path)
print(f"文件 '{file_path}' 已删除")
except Exception as e:
print(f"删除失败: {e}")
else:
print(f"文件 '{file_path}' 不存在")
批量删除符合模式的文件
import os
import glob
# 删除所有 .txt 文件
for file_path in glob.glob("*.txt"):
try:
os.remove(file_path)
print(f"已删除: {file_path}")
except Exception as e:
print(f"删除 {file_path} 失败: {e}")
使用 shutil 删除非空目录
import shutil
# 删除整个目录及其内容
try:
shutil.rmtree("my_folder")
print("目录已成功删除")
except FileNotFoundError:
print("目录不存在")
except Exception as e:
print(f"删除目录时出错: {e}")
安全删除示例
import os
def safe_delete_file(file_path):
"""
安全删除文件的函数
"""
if not os.path.exists(file_path):
print(f"文件 '{file_path}' 不存在")
return False
if os.path.isdir(file_path):
print(f"'{file_path}' 是目录,不是文件")
return False
try:
os.remove(file_path)
print(f"文件 '{file_path}' 已成功删除")
return True
except PermissionError:
print(f"没有权限删除文件 '{file_path}'")
return False
except OSError as e:
print(f"删除文件时发生系统错误: {e}")
return False
# 使用示例
safe_delete_file("important_document.txt")
注意事项
- 文件权限:确保有足够的权限删除文件
- 文件锁定:文件被其他程序打开时无法删除
- 不可恢复:
os.remove()删除的文件通常无法从回收站恢复 - 相对路径:注意当前工作目录,建议使用绝对路径
推荐方法:对于现代Python开发,推荐使用 pathlib 模块,因为它提供了更面向对象的接口和更好的跨平台兼容性。