Search code examples
pythonlistlistdir

How to create a python list with the number of file in each sub directory of a directory


I have a main directory(root) which countain 6 sub directory. I would like to count the number of files present in each sub directory and add all to a simple python list.

For this result : mylist = [497643, 5976, 3698, 12, 456, 745]

I'm blocked on that code:

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))

My trying for the list fill doesn't work and i'm dramaticaly at my best...

Finding a way to iterate sub-directory of a main directory and fill a list with a function applied on each sub directory would sky rocket the speed of my actual data science project!

Thanks for your help

Abel


Solution

  • You can use os.path.isfile and os.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)
    

    Using the for loop

    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)))))