1 import os
2 import stat
3
4 def remove_readonly(func,path): #定义回调函数
5 os.chmod(path,stat.S_IWRITE) #删除文件的只读文件
6 func(path) #在次调用刚刚失败的函数
7
8 def del_dir(path,onerror=None): #path为路径
9 for file in os.listdir(path):
10 file_or_dir = os.path.join(path,file)
11 if os.path.isdir(file_or_dir) and not os.path.islink(file_or_dir):
12 del_dir(file_or_dir) #递归删除只文件夹及其文件
13 else:
14 try:
15 os.remove(file_or_dir) #尝试删除该文件
16 except:
17 if onerror and callable(onerror):
18 onerror(os.remove,file_or_dir) #自动调用回调函数
19 else:
20 print('You have an exception but did not capture it.')
21 os.rmdir(path) #删除文件夹
22
23 del_dir('/Users/c2apple/Desktop/未命名文件夹 3',remove_readonly) #调用函数,指定回调函数