如何使用 os.scandir() 也取回空目录名和非空目录名
How to use os.scandir() to also get back empty and non-empty directory names
在 中递归返回目录结构中所有文件名的解决方案如下所示。
我还需要目录结构中每个子目录的信息以及文件和目录的完整路径名。所以如果我有这个结构:
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)
无论当前条目是否为目录,您都应该生成当前条目。如果它是目录,您还递归获取内容。
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)
在
我还需要目录结构中每个子目录的信息以及文件和目录的完整路径名。所以如果我有这个结构:
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)
无论当前条目是否为目录,您都应该生成当前条目。如果它是目录,您还递归获取内容。
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)