简体   繁体   English

如何在python中删除文件夹? rmtree onerror

[英]How to remove folder in python? rmtree onerror

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: 我最近遇到了麻烦:我需要一个函数来删除Windows中的整个文件夹,所以我进行了搜索,这就是我得到的:

How do I remove/delete a folder that is not empty with Python? 如何使用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)... 答案似乎还不错,这对我来说似乎有些混乱和庞大……在使用shutil.rmtree访问Windows中的文件时,应该有一种更好的方法来解决oneerror(引发试图访问只读文件的错误)。 。

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 : 我只是做了一个更改文件写许可模式的函数,然后使用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: 然后在使用rmtree ,将其添加到onerror参数:

import shutil
shutil.rmtree(desiredpath, onerror = redo_with_write)

Hope it helps to someone with the same trouble I get. 希望它对遇到我同样麻烦的人有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM