Python 如何使用os.scandir()同时获取空目录名和非空目录名

Python 如何使用os.scandir()同时获取空目录名和非空目录名,python,scandir,yield-from,Python,Scandir,Yield From,在本例中,递归返回目录结构中所有文件名的解决方案如下所示 我还需要有关目录结构中每个子目录的信息以及文件和目录的完整路径名。如果我有这样的结构: ls -1 -R .: a b ./a: fileC ./b: 我需要: /a /b /a/fileC 为了实现这一点,我必须如何改变上述答案的解决方案?为了完成,答案如下: try: from os import scandir except ImportError: from scandir import scandir

在本例中,递归返回目录结构中所有文件名的解决方案如下所示

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

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)
试试看:
从操作系统导入scandir
除恐怖外:
从scandir导入scandir#在Python<3.5上使用scandir PyPI模块
def扫描树(路径):
“”“递归生成给定目录的目录项对象。”“”
对于scandir中的条目(路径):
如果条目.is_dir(follow_symlinks=False):
scantree的收益(entry.path)#Python 2.x见下文
其他:
收益率条目
如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
导入系统
对于扫描树中的条目(如果len(sys.argv)>1 else'',则sys.argv[1]:
打印(entry.path)

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

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)

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

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)

谢谢,你的回答帮助了我:)谢谢,你的回答帮助了我:)