如何使用 map() 和 filter() 函数而不是 for 循环删除 Python 3 的空目录?

How to remove empty directories with Python 3 using map() and filter() functions instead of for loop?

我正在尝试使用 Python 3 创建一个函数,该函数使用函数式编程风格删除指定目录中的空目录。

不幸的是,我的尝试没有成功,所以我将不胜感激任何帮助、指导和建议。

我试图让函数执行的操作示例:

之前...

-folder/
    |-empty1/
    |-empty2/
    |-not_empty1/
        |-file
    |-not_empty2/
        |-file

之后...

-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)

谢谢!

编辑:

  1. 删除了第一个映射使用 list(map(...))print 语句调试的末尾的额外括号

  2. path.join() 行移动到 path.isdir()

    上方
  3. 将问题的标题从“...Python FP 样式的 3”更改为因为正如评论中指出的那样,这不是 FP[= 的正确实现和应用18=]

os.rmdir 仅删除空目录,因此在正确且最小的实现中,函数式风格无需执行任何操作:

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