如何在Windows中使用Python删除只读attrib目录?

pro*_*eek 40 python windows attributes

我有一个从版本控制目录复制的只读目录,该目录被锁定. 在此输入图像描述

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

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

Mar*_*ark 52

如果您使用的是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 )
Run Code Online (Sandbox Code Playgroud)

现在,公平地说,可以出于各种原因调用错误函数.'func'参数可以告诉你什么函数"失败"(os.rmdir()或os.remove()).你在这里做什么取决于你想要你的rmtree如何防弹.如果它真的只是需要将文件标记为可写的情况,那么你可以做我上面做的事情.如果您想要更加小心(即确定目录是否未被删除,或者在尝试删除文件时文件是否存在共享冲突),则必须将相应的逻辑插入到on_rm_error()函数中.

  • 凉!这是更专注的方法. (2认同)
  • 对我来说,这是使用 Shutil.rmtree 安全删除 .git 文件夹(包括只读文件)和 .git 文件的唯一有效方法! (2认同)

YOU*_*YOU 10

没有经过测试,但它会像启用写访问一样.

import os, stat

os.chmod(ur"file_path_name", stat.S_IWRITE)
Run Code Online (Sandbox Code Playgroud)

您可能需要与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)
Run Code Online (Sandbox Code Playgroud)


Mik*_*een 5

我用过的方法是:

if os.path.exists(target) :
    subprocess.check_call(('attrib -R ' + target + '\\* /S').split())
    shutil.rmtree(target)
Run Code Online (Sandbox Code Playgroud)

在任何人跳过我之前,我知道这是非常恐怖的,但它可能比上面给出的更传统的答案更简单,并且是可靠的.

我不确定目录上的读/写属性会发生什么.但它还不是一个问题.


zou*_*umi 5

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)
Run Code Online (Sandbox Code Playgroud)

复制自:http ://code.activestate.com/recipes/303343-changing-file-attributes-on-windows/


Tom*_*dor 5

可接受的答案几乎是正确的,但是在只读子目录的情况下可能会失败。

该函数作为rmtreeonerror处理程序的参数提供。

我会建议:

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)
Run Code Online (Sandbox Code Playgroud)

万一该功能再次失败,您可以查看原因,然后继续删除。