在遍歷或搜索文件系統(tǒng)時,如果目錄的文件很多,目錄結(jié)果復(fù)雜,可能會消耗較多的內(nèi)存來保存已遍歷的信息,所以使用Generator就是一個比較好的選擇。另外,使用Recursion會降低代碼量,使代碼可讀性更強。
遍歷目錄,返回所有的文件和目錄
def scan_dir_gen(dir_path):
"""Scan directory recursively and yield all files and directories.
Args:
dir_path: Path object to be scanned.
"""
if dir_path is None or not isinstance(dir_path, Path):
raise TypeError('dir_path must be a Path object')
# The current directory.
yield dir_path
for path in dir_path.iterdir():
if path.is_dir():
# Recursively tranverse the directory.
yield from scan_dir_gen(path)
else:
yield path
遍歷目錄,只返回只有文件的目錄
def dir_only_has_files_gen(dir_path):
"""Scan the directory recursively and returns directories which contain only files.
Args:
dir_path: Path object to be scanned.
"""
if dir_path is None or not isinstance(dir_path, Path):
raise TypeError('dir_path must be a Path object')
has_dir = False
for path in dir_path.iterdir():
if path.is_dir():
has_dir = True
yield from dir_only_has_files_gen(path)
if not has_dir:
yield dir_path