How to remove folder in python? rmtree onerror

99封情书 提交于 2020-02-03 11:02:08

问题


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:

How do I remove/delete a folder that is not empty with Python? empty-with-python

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)...


回答1:


I want to share an easy way that works for me.

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)

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.



来源:https://stackoverflow.com/questions/12990112/how-to-remove-folder-in-python-rmtree-onerror

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!