【问题标题】:Deleting hidden directories? [duplicate]删除隐藏目录? [复制]
【发布时间】:2019-09-05 11:35:04
【问题描述】:

我有一个目录,目录树中的任何位置都可以有.unwanted 目录。我想删除这些。

import shutil
shutil.rmtree('.unwanted', onerror=True)

这不起作用,因为目录是隐藏的。输出:

Traceback (most recent call last):
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\shutil.py", line 374, in _rmtree_unsafe
    with os.scandir(path) as scandir_it:
FileNotFoundError: [WinError 3] The system cannot find the path specified: '.unwanted'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "D:/SYSTEM/CODING/PYTHON/import.py", line 31, in <module>
    shutil.rmtree('.unwanted', onerror=True)
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\shutil.py", line 516, in rmtree
    return _rmtree_unsafe(path, onerror)
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\shutil.py", line 377, in _rmtree_unsafe
    onerror(os.scandir, path, sys.exc_info())
TypeError: 'bool' object is not callable

Process finished with exit code 1

别管行号,示例代码来自一个更大的脚本。

【问题讨论】:

标签: python python-3.x


【解决方案1】:

你可以试试:

import os
os.system("rm -rf .directory_name")

【讨论】:

  • 'rm' is not recognized as an internal or external command, operable program or batch file.
  • 这是 Linux 命令,请改用 Windows 命令。
  • 哦,明白了。我尝试了os.system("for /d /r %u in (.unwanted) do rd /s /q %u"),但出现了很多错误the system cannot find the file/path specified),并且.unwanted 目录仍然存在。它必须在整个树中删除它们。
【解决方案2】:

您的 onerror 调用似乎有误?也许你想写以下内容?

import shutil
shutil.rmtree('.unwanted', ignore_errors=True)

参数 'onerror' 指定一个处理程序。

来自文档:如果提供了 onerror,它必须是一个接受三个参数的可调用对象:函数、路径和 excinfo。

见官方文档https://docs.python.org/3/library/shutil.html

【讨论】:

  • 这也只会直接删除根目录下的那个
【解决方案3】:

@OcasoProtal 提供的链接中找到的解决方案几乎不需要修改,尽管其中一些仍然是个谜。欢迎评论。

import shutil
for root, subdirs, files in os.walk('.'):
    for d in subdirs:
        if d == ".unwanted":
            shutil.rmtree(os.path.join(root, d))

【讨论】:

  • root 是你从 os.walk 得到的当前路径,所以你不能放弃它。 os.walk 返回一个 3 元组,您可能不需要该元组中的所有内容,但删除它并不好。只需添加一个打印语句,您就会看到 ;)
  • 所以我可以将for root, subdirs, files in os... 更改为for subdirs in os...,因为.unwanted 目录不能位于根目录中,也不能是文件。 ..?
  • 不,你不能。但我怀疑你可以放弃for ... subdirs 循环。不幸的是,我目前手头没有 python 来测试它。只需在for root, subdirs, files in os.walk('.'): 之后打印所有三个元素,您就会看到 os.walk 是如何工作的(或使用调试器单步执行代码并检查变量)
  • 是的,另一个 if 应该就足够了,即使只是在 root 中。但是您需要os.remove,因为 rmtree 仅适用于目录。不要忘记import os。正如我所说:如果您不确定只需添加打印而不是 rmtree/os.remove
  • 你是help-vampire!使用try/except,请使用python tutorial
猜你喜欢
  • 2021-05-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-18
  • 1970-01-01
  • 1970-01-01
  • 2012-03-05
  • 2013-12-27
相关资源
最近更新 更多