【发布时间】:2018-04-05 05:07:40
【问题描述】:
使用 Python 2.7 和 scandir,我需要遍历所有目录和子目录并仅返回目录列表。不是文件。路径中子目录的深度可能会有所不同。
我知道 os.walk,但我的目录有 200 万个文件,因此 os.walk 会因此变慢。
目前下面的代码适用于我,但我怀疑可能有更简单的方法/循环来实现相同的结果,我想知道如何改进它。另外我的功能的限制是它仍然受到我可以遍历到子目录的深度的限制,也许这可以克服。
def list_directories(path):
dir_list = []
for entry in scandir(path):
if entry.is_dir():
dir_list.append(entry.path)
for entry2 in scandir(entry.path):
if entry2.is_dir():
dir_list.append(entry2.path)
for entry3 in scandir(entry2.path):
if entry3.is_dir():
dir_list.append(entry3.path)
for entry4 in scandir(entry3.path):
if entry4.is_dir():
dir_list.append(entry4.path)
for entry5 in scandir(entry4.path):
if entry5.is_dir():
dir_list.append(entry5.path)
for entry6 in scandir(entry5.path):
if entry6.is_dir():
dir_list.append(entry6.path)
return dir_list
for item in filelist_dir(directory):
print item
如果您有更好的选择来快速返回包含数百万个文件的路径中的所有目录和子目录,请告诉我。
【问题讨论】:
标签: python directory-structure subdirectory scandir