Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Remove empty folders recursively

Tags:

python

I'm having troubles finding and deleting empty folders with my Python script. 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. 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)
like image 840
z4k4 Avatar asked Jan 20 '16 12:01

z4k4


2 Answers

use insted the function

os.removedirs(path)

this will remove directories until the parent directory is not empty.

like image 158
latorrefabian Avatar answered Oct 28 '22 22:10

latorrefabian


Ideally, you should remove the directories immediately after deleting the files, rather than doing two passes with 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)
like image 37
sirlark Avatar answered Oct 29 '22 00:10

sirlark