"删除隐藏目录?"

2024-05-14 01:26:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个目录,目录树中的任何地方都可以有.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

不管行号是多少,示例代码都来自更大的脚本。你知道吗


Tags: pathinpy目录locallineusersappdata
3条回答

你从onerror打来的电话好像错了?也许你想写以下内容?你知道吗

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

参数'onerror'指定处理程序。你知道吗

从文档中可以看出:如果提供了onerror,那么它必须是一个可调用的,接受三个参数:function、path和exinfo。你知道吗

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

@OcasoProtal提供的链接中找到的解决方案几乎没有修改,尽管其中一些仍然是个谜。欢迎评论。你知道吗

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

您可以尝试:

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

相关问题 更多 >