简体   繁体   English

Python:递归删除空文件夹

[英]Python: Remove empty folders recursively

I'm having troubles finding and deleting empty folders with my Python script.我在使用 Python 脚本查找和删除空文件夹时遇到了麻烦。 I have some directories with files more or less like this:我有一些目录的文件或多或少是这样的:

A/
--B/
----a.txt
----b.pdf
--C/
----d.pdf

I'm trying to delete all files which aren't PDFs and after that delete all empty folders.我正在尝试删除所有不是 PDF 的文件,然后删除所有空文件夹。 I can delete the files that I want to, but then I can't get the empty directories.我可以删除我想要的文件,但是我无法获得空目录。 What I'm doing wrong?我做错了什么?

    os.chdir(path+"/"+name+"/Test Data/Checklists")
    pprint("Current path: "+ os.getcwd())
    for root, dirs, files in os.walk(path+"/"+name+"/Test Data/Checklists"):
            for name in files:
                    if not(name.endswith(".pdf")):
                            os.remove(os.path.join(root, name))
    pprint("Deletting empty folders..")
    pprint("Current path: "+ os.getcwd())
    for root, dirs, files in os.walk(path+"/"+name+"/Test Data/Checklists", topdown=False):
            if not dirs and not files:
                    os.rmdir(root)

use insted the function使用插入的函数

os.removedirs(path)

this will remove directories until the parent directory is not empty.这将删除目录,直到父目录不为空。

Ideally, you should remove the directories immediately after deleting the files, rather than doing two passes with os.walk理想情况下,您应该在删除文件后立即删除目录,而不是使用os.walk进行两次传递

import sys
import os

for dir, subdirs, files in os.walk(sys.argv[1], topdown=False):
    for name in files:
        if not(name.endswith(".pdf")):
            os.remove(os.path.join(dir, name))

    # check whether the directory is now empty after deletions, and if so, remove it
    if len(os.listdir(dir)) == 0:
        os.rmdir(dir)

For empty folders deletion you can use this snippet.对于空文件夹删除,您可以使用此代码段。 It can be combined with some files deletion, but as last run should be used as is.它可以与一些文件删除结合使用,但应按原样使用上次运行。

import os


def drop_empty_folders(directory):
    """Verify that every empty folder removed in local storage."""

    for dirpath, dirnames, filenames in os.walk(directory, topdown=False):
        if not dirnames and not filenames:
            os.rmdir(dirpath)

remove all empty folders删除所有空文件夹

import os 
folders = './A/'  # directory
for folder in list(os.walk(folders)) :
    if not os.listdir(folder[0]):
        os.removedirs(folder[0])



声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM