You can scan recursively using os.walk()
, or if you need DirEntry
objects or more control, write a recursive function like scantree()
below:
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)
Notes:
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…