windows 系统 python shutil.rmtree 在递归删除目录时会报以下错误
import os, stat
import shutil
shutil.rmtree('a/f')
PermissionError: [WinError 5] 拒绝访问。: 'a/f\\c'
PermissionError: [WinError 5] 拒绝访问。: ‘a/f\c’
检查了下文件夹,发现里面的文件都被删了,只是留下了几个空文件夹。
查了下资料发现,之所以会这样,是因为某些文件设置了只读属性位。
我们可以通过设置onerror错误回调函数来改变这些只读属性位,然后再次删除就好了
import os, stat
import shutil
def remove_readonly(func, path, _): # 错误回调函数,改变只读属性位,重新删除
"Clear the readonly bit and reattempt the removal"
os.chmod(path, stat.S_IWRITE)
func(path)
shutil.rmtree('a/f', onerror=remove_readonly) # 设置错误回调函数οnerrοr=remove_readonly
版权声明:本文为qq_21444067原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。