Net*_*ave 2 python windows file onerror
我最近遇到了这个麻烦:我需要一个删除Windows中完全文件夹的函数,所以我搜索了这就是我得到的:
如何删除/删除Python不为空的文件夹? 空带,蟒蛇
答案,看起来还不错,对我来说似乎有点混乱和大...在使用shutil.rmtree访问windows中的文件时应该有更好的方法来解决oneerror(尝试访问只读文件时出错). .
我想分享一个适合我的简单方法.
我刚刚创建了一个更改文件写入权限模式的函数,然后将其删除os.remove:
import stat # needed for file stat
# arguments: the function that failed, the path
# it failed on, and the error that occurred.
def redo_with_write(redo_func, path, err):
os.chmod(path, stat.S_IWRITE)
redo_func(path)
Run Code Online (Sandbox Code Playgroud)
然后在使用时rmtree,将其添加到onerror参数中:
import shutil
shutil.rmtree(desiredpath, onerror = redo_with_write)
Run Code Online (Sandbox Code Playgroud)
希望对我遇到同样麻烦的人有所帮助.