1

尝试使用 python 脚本自动删除文件,我得到:

Traceback (most recent call last):
  Python script "5", line 8, in <module>
    shutil.rmtree(os.path.join(root, d))
  File "shutil.pyc", line 221, in rmtree
  File "shutil.pyc", line 219, in rmtree
WindowsError: [Error 5] Access is denied: 'C:\\zDump\\TVzip\\Elem.avi'

使用这个

import os
import shutil

for root, dirs, files in os.walk(eg.globals.tvzip):
    for f in files:
        os.remove(os.path.join(root, f))
    for d in dirs:
        shutil.rmtree(os.path.join(root, d))

for root, dirs, files in os.walk(eg.globals.tvproc):
    for f in files:
        os.remove(os.path.join(root, f))
    for d in dirs:
        shutil.rmtree(os.path.join(root, d))

一切都以管理员身份运行,有什么帮助吗?

4

2 回答 2

1

虽然我无法评论 Windows 权限(或缺少权限),但假设您有正确的权限,那么打开文件句柄真的很可能。

我只是想提一下,shutil.rmtree 将清除它删除的目录中的所有文件......所以你可以将你的算法切成两半,并停止一个接一个地删除文件。

于 2013-11-01T14:48:42.133 回答
0

通常,当您尝试删除的路径是read-only. 您可以尝试以下可能有效的方法:

import stat
import os

def make_dir_writable(function, path, exception):
    """The path on Windows cannot be gracefully removed due to being read-only,
    so we make the directory writable on a failure and retry the original function.
    """
    os.chmod(path, stat.S_IWRITE)
    function(path)

if os.path.exists(path):
    shutil.rmtree(path, onerror=make_dir_writable)

可以在此处找到有关该主题的文档:https ://docs.python.org/3.9/library/shutil.html#shutil.rmtree

于 2022-02-23T03:02:52.137 回答