我最近遇到了这个麻烦:我需要一个功能来删除 Windows 中的整个文件夹,所以我进行了搜索,这就是我得到的:
如何使用 Python 删除/删除不为空的文件夹? https://stackoverflow.com/questions/303200/how-do-i-remove-delete-a-folder-that-is-not-空与 python
答案,看起来不错,对我来说似乎有点令人困惑和大...应该有一个更好的方法来解决使用shutil.rmtree访问Windows中的文件时的一个错误(尝试访问只读文件时引发错误).. 。
我想分享一个适合我的简单方法。
我刚刚做了一个函数来更改文件的写权限模式,然后用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)
然后当使用rmtree
,将其添加到onerror
范围:
import shutil
shutil.rmtree(desiredpath, onerror = redo_with_write)
希望它对与我遇到同样问题的人有所帮助。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)