废话不多说,上代码
def delete_dirs(path):
"""删除文件夹下所有的文件和子目录"""
for root, dirs, files in os.walk(path):
for name in files:
file_path = os.path.join(root, name)
if os.path.exists(file_path):
try:
os.remove(file_path)
except:
pass
for name in dirs:
dir_path = os.path.join(root, name)
if os.path.exists(dir_path):
try:
os.rmdir(dir_path)
except:
pass
# 如果只是想删除path下的文件和文件夹,保留path,就把下面的代码注释掉
if os.path.exists(path):
try:
os.rmdir(path)
except:
delete_dirs(path)