【发布时间】:2020-08-28 19:30:26
【问题描述】:
我有一个包含 6 个子目录的主目录(根目录)。 我想计算每个子目录中存在的文件数并将所有文件添加到一个简单的 python 列表中。
对于这个结果:mylist = [497643, 5976, 3698, 12, 456, 745]
我在该代码上被阻止:
import os, sys
list = []
# Open a file
path = "c://root"
dirs = os.listdir( path )
# This would print all the files and directories
for file in dirs:
print (file)
#fill a list with each sub directory number of elements
for sub_dir in dirs:
list = dirs.append(len(sub_dir))
我尝试填写列表没有用,我正处于最佳状态...
找到一种方法来迭代主目录的子目录并使用应用于每个子目录的函数填充列表将大大提高我实际数据科学项目的速度!
感谢您的帮助
亚伯
【问题讨论】:
-
使用
os.walk()会有很大帮助。它递归地向下钻取子目录。