此批处理 FOR 命令如何转换为 python?

how does this batch FOR command translate to python?

我一直在试图弄清楚如何将这个简单的批处理代码(删除树中的每个空目录)转换为 python,这花费了我不合理的时间。我恳请提供一个有详细解释的解决方案,我相信它会快速启动我对语言的理解。我有放弃的危险。

for /d /r %%u in (*) do rmdir "%%u"

我确实有我正在尝试修复的怪诞版本,其中一定有各种各样的错误。如果合适,我更愿意使用 shutil 模块。

for dirpath in os.walk("D:\SOURCE")
    os.rmdir(dirpath)

如果您只想删除空目录,那么 pathlib.Path(..).glob(..) 可以:

import os
from pathlib import Path
emptydirs = [d for d in Path('.').glob('**/*')          # go through everything under '.'
             if d.is_dir() and not os.listdir(str(d))]  # include only directories without contents
for empty in emptydirs:    # iterate over all found empty directories
    os.rmdir(empty)        # .. and remove

如果要删除目录下的所有内容,那么shutil.rmtree(..)函数一行即可完成:

import shutil
shutil.rmtree('.')

查看文档了解所有详细信息 (https://docs.python.org/2/library/shutil.html#shutil.rmtree)