python 删除文件、目录(文件夹)
最近使用 python 进行文件,目录的操作,实在难以相信,python 这么简单,易用的语言,竟然没有一个库很好的支持删除文件、目录(文件夹),于是把最近收集到的一些信息做下整理。
删除文件:
Pathlib : file_path.unlink()
os : os.remove(file_path)
删除目录(文件夹):
空目录(Path 库) : dir_path.rmdir()
非空目录(shutil):shutil.rmtree(dir_to_delete)
删除文件
Pathlib
from pathlib import Path
# 定义要删除的文件路径
file_to_delete = Path('/home/python/test/file1.txt')
try:
# 检查文件是否存在
if file_to_delete.exists() and file_to_delete.is_file():
# 删除文件
file_to_delete.unlink()
print(f"File {file_to_delete} has been deleted.")
else:
print(f"File {file_to_delete} does not exist or is not a file.")
except Exception as e:
print(f"An error occurred: {e}")
os
import os
# 定义要删除的文件路径
file_to_delete = '/home/python/test/file1.txt'
try:
# 检查文件是否存在
if os.path.exists(file_to_delete) and os.path.isfile(file_to_delete):
# 删除文件
os.remove(file_to_delete)
print(f"File {file_to_delete} has been deleted.")
else:
print(f"File {file_to_delete} does not exist or is not a file.")
except Exception as e:
print(f"An error occurred: {e}")
删除目录
使用 pathlib
删除空目录
from pathlib import Path
# 定义要删除的目录路径
dir_to_delete = Path('/home/python/test/empty_dir')
# 检查目录是否存在并且是空目录
if dir_to_delete.exists() and dir_to_delete.is_dir():
try:
# 删除空目录
dir_to_delete.rmdir()
print(f"Directory {dir_to_delete} has been deleted.")
except OSError as e:
print(f"Error: {e}")
else:
print(f"Directory {dir_to_delete} does not exist or is not a directory.")
使用 shutil
递归删除非空目录
import shutil
from pathlib import Path
# 定义要删除的目录路径
dir_to_delete = Path('/home/python/test/non_empty_dir')
# 检查目录是否存在并且是目录
if dir_to_delete.exists() and dir_to_delete.is_dir():
try:
# 递归删除目录及其所有内容
shutil.rmtree(dir_to_delete)
print(f"Directory {dir_to_delete} and its contents have been deleted.")
except PermissionError as e:
print(f"Permission error: {e}")
except FileNotFoundError as e:
print(f"File not found: {e}")
except Exception as e:
print(f"An unexpected error occurred: {e}")
else:
print(f"Directory {dir_to_delete} does not exist or is not a directory.")
整合后的函数
import os
import shutil
from pathlib import Path
def delete_path(path):
"""
删除给定的路径,可以是文件、空目录或非空目录。
:param path: 要删除的路径(字符串或 Path 对象)
:return: None
"""
# 将输入转换为 Path 对象
if not isinstance(path, Path):
path = Path(path)
try:
if path.exists():
if path.is_file():
# 如果是文件,直接删除
path.unlink()
print(f"File {path} has been deleted.")
elif path.is_dir():
# 如果是目录,检查是否为空
if any(path.iterdir()):
# 如果是非空目录,递归删除
shutil.rmtree(path)
print(f"Non-empty directory {path} and its contents have been deleted.")
else:
# 如果是空目录,直接删除
path.rmdir()
print(f"Empty directory {path} has been deleted.")
else:
print(f"The path {path} does not exist.")
except Exception as e:
print(f"An error occurred while deleting {path}: {e}")
作者:2301_78094384