gpt4 book ai didi

python - 如何在 Windows 中使用 Python 删除只读属性目录?

转载 作者:可可西里 更新时间:2023-11-01 10:42:22 26 4
gpt4 key购买 nike

我有一个从锁定的版本控制目录复制的只读目录。 enter image description here

当我尝试使用 shutil.rmtree(TEST_OBJECTS_DIR) 命令删除此目录时,我收到以下错误消息。

WindowsError: [Error 5] Access is denied: 'C:\...\environment.txt'
  • 问:如何更改整个目录结构中所有内容的属性?

最佳答案

如果您正在使用 shutil.rmtree,您可以使用该函数的 onerror 成员来提供一个接受三个参数的函数:函数、路径和异常信息。在删除树时,您可以使用此方法将只读文件标记为可写。

import os, shutil, stat

def on_rm_error( func, path, exc_info):
# path contains the path of the file that couldn't be removed
# let's just assume that it's read-only and unlink it.
os.chmod( path, stat.S_IWRITE )
os.unlink( path )

shutil.rmtree( TEST_OBJECTS_DIR, onerror = on_rm_error )

现在,公平地说,调用错误函数的原因有多种。 'func' 参数可以告诉您哪个函数“失败”(os.rmdir() 或 os.remove())。您在这里做什么取决于您希望 rmtree 的防弹程度。如果真的只是需要将文件标记为可写的情况,您可以执行我上面所做的。如果您想更加小心(即确定目录是否无法删除,或者在尝试删除文件时是否存在共享冲突),则必须将适当的逻辑插入到 on_rm_error() 函数中.

关于python - 如何在 Windows 中使用 Python 删除只读属性目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45688888/

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