gpt4 book ai didi

python - 如何删除python中的文件夹? rmtree错误

转载 作者:可可西里 更新时间:2023-11-01 09:45:56 29 4
gpt4 key购买 nike

我最近遇到了这个麻烦:我需要一个功能来删除 Windows 中的整个文件夹,所以我搜索了一下,这就是我得到的:

How do I remove/delete a folder that is not empty with Python?用 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)

希望它能帮助遇到同样问题的人。

关于python - 如何删除python中的文件夹? rmtree错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12990112/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com