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

标签 python windows attributes

我有一个从已锁定的版本控制目录复制的只读目录。 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/4829043/

相关文章:

c# - XML 序列化 - 禁用呈现数组的根元素

python - 为什么我的 python 子类无法识别父类(super class)的属性?

c# - 如何将OperationContract应用到接口(interface)中的所有方法

python 类属性

python - 根据另一个索引值修改 DataFrame 索引中的值

python - 用于评估的 Tensorflow 平均绝对误差 (MAE)

java程序使操作系统难以格式化可移动磁盘

python - 如何在python和streamlit中下载excel文件?

c++ - 微软的 CopyFileEx 错误

sql-server - 如何通过 SQL Server xp_cmdshell 在 Windows 命令 shell 中根据创建日期加载文件