如何使用目录的每个子目录中的文件数创建python列表

问题描述

我有一个主目录(root),该目录包含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.listdir。当前代码仅占用文件路径的长度。

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:
    temp = os.listdir(sub_dir)
    list = dirs.append(len(temp))

将此行添加到代码中将列出子目录

,

您快到了:

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)

for sub_dir in dirs:
    if os.path.isdir(sub_dir):
        list.append(len(os.listdir(os.path.join(path,sub_dir))))

print(list)
,

您可以使用os.path.isfileos.path.isdir

res = [len(list(map(os.path.isfile,os.listdir(os.path.join(path,name))))) for name in os.listdir(path) if os.path.isdir(os.path.join(path,name))]
print(res)

使用for循环

res = []
for name in os.listdir(path):
    dir_path = os.path.join(path,name)
    if os.path.isdir(dir_path):
        res.append(len(list(map(os.path.isfile,os.listdir(dir_path)))))
,

作为替代方案,您也可以使用glob模块来完成此任务和其他相关任务。 我创建了一个test目录,其中包含3个子目录lmk,每个目录包含3个测试文件。

import os,glob
  
list = []
path = "test" # you can leave this "." if you want files in the current directory

for root,dirs,files in os.walk(path,topdown=True):
   for name in dirs:
     list.append(len(glob.glob(root + '/' +  name + '/*')))

print(list)

输出:

[3,3,3]