如何在python中删除文件夹? rmtree onerror [英] How to remove folder in python? rmtree onerror
问题描述
我最近遇到了麻烦:我需要一个函数来删除Windows中的整个文件夹,所以我进行了搜索,这就是我得到的:
I've recently have this trouble: I needed a function that removes an entirely folder in windows so I searched and this is what I get:
如何删除/删除文件夹那不是Python空的吗? empty-with-python
How do I remove/delete a folder that is not empty with Python? empty-with-python
看起来不错的答案,对我来说似乎有点混乱和庞大……使用shutil.rmtree在Windows中访问文件时,应该有一种更好的方法来解决oneerror(引发尝试访问只读文件的错误)...
The answers, that looks ok, seems a bit confusing and large for me... there should be a better way to solve the oneerror while accesing files in windows with shutil.rmtree (raise an error trying to acces read only files)...
推荐答案
我想分享一种对我有用的简单方法.
I want to share an easy way that works for me.
我刚刚做了一个函数,可以更改文件的写许可模式,然后用os.remove
删除它:
I just made a function that changes the write permission mode of the file, and then deletes it with 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
参数:
then when using rmtree
, add it to the onerror
parameter:
import shutil
shutil.rmtree(desiredpath, onerror = redo_with_write)
希望它对遇到我同样麻烦的人有所帮助.
Hope it helps to someone with the same trouble I get.
这篇关于如何在python中删除文件夹? rmtree onerror的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!