一、os.rmdir(path)
删除目录 path,path必须是个空目录,否则抛出oserror异常。
import os
os.rmdir('./test') # test是一个空的文件夹二、os.removedirs(path)
递归地删除目录。要求每一级目录都为空,才能递归删除全部目录。子目录被成功删除,才删除父目录;如果子目录没有成功删除,将抛出oserror异常。
import os
#test2是test的子文件夹,如果test2不为空,则抛出异常;如果test2为空,test不为空,则test2删除成功,test不删除,但不报异常
os.removedirs('./test/test2)三、shutil.rmtree(path)
不管目录path是否为空,都删除。
import shutil
shutil.rmtree('./test') # 删除test文件夹下所有的文件、文件夹四、删除文件
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}")到此这篇关于python删除目录的三种方法的文章就介绍到这了,更多相关python删除目录内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论