I'm trying to create a function with Python 3 that deletes empty directories in a specified directory.
Unfortunately, my attempts haven't been successful, so I'd appreciate any help, guidance, and suggestions.
Before...
-folder/
|-empty1/
|-empty2/
|-not_empty1/
|-file
|-not_empty2/
|-file
🔽
After...
-folder/
|-not_empty1/
|-file
|-not_empty2/
|-file
# folder - absolute path to directory that may contain empty directories
def cleanup(folder):
from os import listdir, rmdir, path
ls = listdir(folder)
ls = map(lambda f: path.join(folder, f), ls)
folders = filter(lambda f: path.isdir(f), ls)
map(lambda x: rmdir(x), folders)
Thanks!
EDITS:
Removed extra parenthesis at the end that the first map had from using list(map(...))
to debug with print
statements
Moved path.join()
line above path.isdir()
Changed the title of the question from "...Python 3 in FP style" since, as pointed out in the comments, this isn't a correct implementation and application of FP.
os.rmdir
only removes empty directories, so there’s nothing left to do in a functional style in a correct and minimal implementation:
import errno
import os
def cleanup(folder):
for name in os.listdir(folder):
try:
os.rmdir(os.path.join(folder, name))
except OSError as e:
if e.errno != errno.ENOTEMPTY:
raise