【Python3】递归删除文件夹下所有文件

主要用到了 os 库

实现过程看代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
def delFiles(path):
"""
删除文件夹下所有文件和文件夹
:reture: 返回删除的文件个数
"""
cnt = 0
for i in os.listdir(path):
file_path = os.path.join(path, i)
if os.path.isfile(file_path):
# 删除文件,必须保证这个路径是个文件
os.unlink(file_path)
cnt += 1
else:
# 文件夹
cnt += delFiles(file_path)
# 删除文件夹,调用此函数必须保证文件夹内为空
os.rmdir(file_path)
return cnt

【Python3】递归删除文件夹下所有文件

https://biteax.com/d14112bd.html

作者

石志超

发布于

2021-12-07

更新于

2023-09-27

许可协议