How to remove empty directories with Python 3 using map() and filter() functions instead of for loop?
Question:
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.
Example of what I’m trying to get the function to do:
Before…
-folder/
|-empty1/
|-empty2/
|-not_empty1/
|-file
|-not_empty2/
|-file
After…
-folder/
|-not_empty1/
|-file
|-not_empty2/
|-file
Here’s what I was sure would work but didn’t:
# 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.
Answers:
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
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.
Example of what I’m trying to get the function to do:
Before…
-folder/
|-empty1/
|-empty2/
|-not_empty1/
|-file
|-not_empty2/
|-file
After…
-folder/
|-not_empty1/
|-file
|-not_empty2/
|-file
Here’s what I was sure would work but didn’t:
# 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 withprint
statements -
Moved
path.join()
line abovepath.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