如何在 Windows 中使用 Python 删除只读 attrib 目录?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4829043/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to remove read-only attrib directory with Python in Windows?
提问by prosseek
I have a read only directory copied from version controlled directory which is locked.

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

When I tried to remove this directory with shutil.rmtree(TEST_OBJECTS_DIR)command, I got the following error message.
当我尝试使用shutil.rmtree(TEST_OBJECTS_DIR)命令删除此目录时,收到以下错误消息。
WindowsError: [Error 5] Access is denied: 'C:\...\environment.txt'
- Q : How can I change the attribute of everything in a wholedirectory structure?
- 问:如何更改整个目录结构中所有内容的属性?
采纳答案by Mark
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.
如果您使用的是 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 )
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.
现在,公平地说,可以出于多种原因调用错误函数。'func' 参数可以告诉您哪个函数“失败”(os.rmdir() 或 os.remove())。你在这里做什么取决于你希望你的 rmtree 是多么的防弹。如果真的只是需要将文件标记为可写的情况,你可以按照我上面做的来做。如果您想更加小心(即确定目录是否无法删除,或者在尝试删除文件时是否存在共享冲突),则必须将适当的逻辑插入到 on_rm_error() 函数中.
回答by YOU
Not tested but It would be, something like to enable write access.
未测试,但它会是,类似于启用写访问。
import os, stat
os.chmod(ur"file_path_name", stat.S_IWRITE)
You may need to combine with os.walk to make everything write enable. something like
您可能需要与 os.walk 结合使用才能使所有内容都可以写入。就像是
for root, dirs, files in os.walk(ur'root_dir'):
for fname in files:
full_path = os.path.join(root, fname)
os.chmod(full_path ,stat.S_IWRITE)
回答by Mike Gleen
The method that I have used is to do:
我使用的方法是:
if os.path.exists(target) :
subprocess.check_call(('attrib -R ' + target + '\* /S').split())
shutil.rmtree(target)
Before anyone jumps on me, I know that this is dreadfully un-pythonic, but it is possibly simpler than the more traditional answers given above, and has been reliable.
在任何人跳到我身上之前,我知道这非常不符合 Python 标准,但它可能比上面给出的更传统的答案更简单,并且一直很可靠。
I'm not sure what happens regarding read/write attributes on directories. But it hasn't been an issue yet.
我不确定目录上的读/写属性会发生什么。但这还不是问题。
回答by zoumi
import win32con, win32api,os
file='test.txt'
#make the file hidden
win32api.SetFileAttributes(file,win32con.FILE_ATTRIBUTE_HIDDEN)
#make the file read only
win32api.SetFileAttributes(file,win32con.FILE_ATTRIBUTE_READONLY)
#to force deletion of a file set it to normal
win32api.SetFileAttributes(file, win32con.FILE_ATTRIBUTE_NORMAL)
os.remove(file)
copy from:http://code.activestate.com/recipes/303343-changing-file-attributes-on-windows/
复制自:http: //code.activestate.com/recipes/303343-changed-file-attributes-on-windows/
回答by Tomasz Gandor
The accepted answer is almost right, but it could fail in case of a read-only subdirectory.
接受的答案几乎是正确的,但如果是只读子目录,它可能会失败。
The function is given as an argument to the rmtree's onerrorhandler.
该函数作为rmtree的onerror处理程序的参数给出。
I would suggest:
我会建议:
import os, shutil, stat
def remove_readonly(fn, path, excinfo):
try:
os.chmod(path, stat.S_IWRITE)
fn(path)
except Exception as exc:
print "Skipped:", path, "because:\n", exc
shutil.rmtree(TEST_OBJECTS_DIR, onerror=remove_readonly)
In case the function fails again, you can see the reason, and continue deleting.
如果功能再次失败,您可以查看原因,并继续删除。

