os.remove() 就是删除文件的 os.removedirs() 就是删除文件夹的 os.path.exists() 用来判断文件或文件夹是否存在
import os
path = "D:\\hello.py"
if(os.path.exists(path)): # 判断文件是否存在
os.remove(path) # 删除文件
path = "D:\\hello"
if(os.path.exists(path)): # 判断文件夹是否存在
os.removedirs(path) # 删除文件夹
默认非空文件夹是不允许删除的,下面的方法可实现非空文件夹的删除。
需要引用到 pathlib 库。
首先 path.glob("**/*")
方法可以显示路径下所有的文件和文件夹。
其中 os.path.isfile()
和 os.path.isdir()
方法可以判断路径是文件还是文件夹。
然后先删除所有的文件,再把剩下的目录添加到列表中进行降序排序,这样外层目录就会排在前面,这种排序删除后就相当于从内到外进行空目录删除了,来达到删除所有目录的效果。
import pathlib
import os
def delete_local_dir(delete_path):
'''
作用: 删除本地目录
参数:需要删除的目录
返回:无
'''
path = pathlib.Path(delete_path)
for i in path.glob("**/*"):
# 删除文件
if(os.path.exists(i)):
if(os.path.isfile(i)):
os.remove(i)
# 将目录内容存为数组,方便排序
a = []
for i in path.glob("**/*"):
a.append(str(i))
# 降序排序后从内层开始删除
a.sort(reverse = True)
for i in a:
# 删除目录
if(os.path.exists(i)):
if(os.path.isdir(i)):
os.removedirs(i)