【问题标题】:How to use os.scandir() to also get back empty and non-empty directory names如何使用 os.scandir() 来取回空目录名和非空目录名
【发布时间】:2020-08-26 08:42:59
【问题描述】:

https://stackoverflow.com/a/33135143 中,递归返回目录结构中所有文件名的解决方案如下所示。

我还需要目录结构中每个子目录的信息以及文件和目录的完整路径名。所以如果我有这个结构:

ls -1 -R
.:
a
b

./a:
fileC

./b:

我需要:

/a
/b
/a/fileC

我必须如何更改上述答案的解决方案才能实现这一目标?为了完整起见,下面给出答案:

try:
    from os import scandir
except ImportError:
    from scandir import scandir  # use scandir PyPI module on Python < 3.5

def scantree(path):
    """Recursively yield DirEntry objects for given directory."""
    for entry in scandir(path):
        if entry.is_dir(follow_symlinks=False):
            yield from scantree(entry.path)  # see below for Python 2.x
        else:
            yield entry

if __name__ == '__main__':
    import sys
    for entry in scantree(sys.argv[1] if len(sys.argv) > 1 else '.'):
        print(entry.path)

【问题讨论】:

    标签: python scandir yield-from


    【解决方案1】:

    无论它是否是目录,您都应该生成当前条目。如果它是一个目录,你递归来获取内容。

    def scantree(path):
        """Recursively yield DirEntry objects for given directory."""
        for entry in scandir(path):
            yield entry
            if entry.is_dir(follow_symlinks=False):
                yield from scantree(entry.path)
    

    【讨论】:

    • 谢谢你的回答对我有帮助:)
    猜你喜欢
    • 2021-03-07
    • 2014-11-14
    • 1970-01-01
    • 2012-03-19
    • 2021-10-05
    • 2010-12-11
    • 2015-04-12
    • 2013-07-23
    • 1970-01-01
    相关资源
    最近更新 更多