如何删除只读与Python ATTRIB目录在Windows? [英] How to remove read-only attrib directory with Python in Windows?

查看:268
本文介绍了如何删除只读与Python ATTRIB目录在Windows?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有从被锁定的版本控制目录复制只读目录。

I have a read only directory copied from version controlled directory which is locked.

当我试图与此目录 shutil.rmtree(TEST_OBJECTS_DIR)命令删除,我得到了以下错误消息。

When I tried to remove this directory with shutil.rmtree(TEST_OBJECTS_DIR) command, I got the following error message.

WindowsError: [Error 5] Access is denied: 'C:\...\environment.txt'


  • 问:我怎样才能改变一切的属性在目录结构

    • Q : How can I change the attribute of everything in a whole directory structure?
    • 推荐答案

      如果您使用的是shutil.rmtree,您可以使用该功能的onerror成员提供一个函数,需要三个params:一个功能,路径和异常信息。您可以使用此方法,而你正在删除您的树,以纪念只读文件,可写的。

      If you are using shutil.rmtree, you can use the onerror member of that function to provide a function that takes three params: function, path, and exception info. You can use this method to mark read only files as writable while you are deleting your tree.

      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 )
      

      现在,为了公平起见,误差函数可以被要求进行各种各样的原因。在'功能'参数可以告诉你什么功能失败(os.rmdir()或os.remove())。你在这里做什么取决于你想如何防弹你rmtree是。如果它真的只是需要以将文件标记为可写的情况下,你可以做我所做的上方。如果你想更谨慎(即确定的目录coudln't被删除,或是否有对文件共享冲突,而试图将其删除),适当的逻辑就必须插入on_rm_error()函数

      Now, to be fair, the error function could be called for a variety of reasons. The 'func' parameter can tell you what function "failed" (os.rmdir() or os.remove()). What you do here depends on how bullet proof you want your rmtree to be. If it's really just a case of needing to mark files as writable, you could do what I did above. If you want to be more careful (i.e. determining if the directory coudln't be removed, or if there was a sharing violation on the file while trying to delete it), the appropriate logic would have to be inserted into the on_rm_error() function.

      这篇关于如何删除只读与Python ATTRIB目录在Windows?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆