Deleting hidden directories? [duplicate]

做~自己de王妃 提交于 2021-02-08 11:39:42

问题


I have a directory where there can be .unwanted directories anywhere within the directory tree. I want these deleted.

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

This does not work because the directories are hidden. Output:

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

Nevermind the line numbers, the sample code is from a larger script.


回答1:


You can try:

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



回答2:


Your call from onerror seems wrong? Maybe you wanted write the following?

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

The param 'onerror' specify an handler.

From the documentation: If onerror is provided, it must be a callable that accepts three parameters: function, path, and excinfo.

See the official documentation https://docs.python.org/3/library/shutil.html




回答3:


The solution found in the link provided by @OcasoProtal works with little modification, although some of it is still a mystery. Comments welcomed.

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


来源:https://stackoverflow.com/questions/57804607/deleting-hidden-directories

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!