0

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

1 回答 1

2

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

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)
于 2020-05-10T21:35:17.640 回答