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

gzjq41n4  于 2022-11-18  发布在  Windows
关注(0)|答案(6)|浏览(143)

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

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

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

6yt4nkrj1#

如果使用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 )

现在,公平地说,调用error函数的原因有很多种。'func'参数可以告诉您哪个函数“失败”(操作系统.rmdir()或操作系统.remove()).您在这里所做的取决于您希望rmtree的安全性如何.如果只是需要将文件标记为可写,你可以做我上面做的。如果你想更小心(即,确定是否无法删除目录,或者在尝试删除文件时是否存在共享冲突),必须将适当的逻辑插入on_rm_error()函数。

0yycz8jy

0yycz8jy2#

未测试,但它将是,类似于启用写访问。

import os, stat

os.chmod(ur"file_path_name", stat.S_IWRITE)

您可能需要与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)
l3zydbqr

l3zydbqr3#

我使用的方法是:

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

在任何人跳到我身上之前,我知道这是可怕的非Python,但它可能比上面给出的更传统的答案更简单,而且是可靠的。
我不知道目录的读/写属性会发生什么,但这还不是一个问题。

u5rb5r59

u5rb5r594#

接受的答案几乎是正确的,但如果是只读子目录,则可能会失败。
该函数作为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)

如果该功能再次失败,您可以查看原因,并继续删除。

isr3a4wc

isr3a4wc5#

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)

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

rpppsulh

rpppsulh6#

您可以使用以下代码从文件夹中删除只读:

import os, stat
from stat import *
import shutil
import fnmatch

file_name = r'<file path>'
os.chmod(file_name, stat.S_IWRITE)
os.remove(file_name)

相关问题