'Count number of file in each subdirectory python

I am trying to get the count of all files listed in all directories as well as the count of files inside individual directories. Below is my code to get the total count of files in all directories but I am unable to get how to get the count within individual directory. Can some one please help?

N = 0 #Total count of number of files in all directories
N_c = 0 #Number of documents in each class

for dirpath, dirnames, filenames in os.walk(filePath):
    for filename in [f for f in filenames]:
        files = [os.path.join(dirpath, filename)]
        for f in files:
            N+=1


Solution 1:[1]

In user7737327 answer: you do not need to iterate over the dirpath and for d in dirpath

filenames contain a list of all files in current directory. We can just take the length of filenames to get the number of files in current directory.

N = 0  # total files
for dirpath, dirnames, filenames in os.walk(file_path):
    N_c = len(filenames)
    N += N_c
    print "Files in ", dirpath, N_c
print "Total Files ",N

Solution 2:[2]

You are working too hard. You have a list of filenames, just take its length. I don't know what you mean by "the count of files inside individual directories" so I am just printing them.

N = 0 #Total count of number of files in all directories
# what is this supposed to be?
# N_c = 0 #Number of documents in each class

for dirpath, dirnames, filenames in os.walk(filePath):
    N += len(filenames)
    print("Files in", dirpath, len(filenames)

print("Total files", N)

Solution 3:[3]

You can use pathlib, a recursive glob and sum:

from pathlib import Path 

fc=sum(1 for fn in Path(ur_path).glob('**/*') if fn.is_file())

If you want a count by directory rather than a total:

dirs={}
for fn in Path(ur_path).glob('**/*'):
    if fn.is_file():
        key=str(fn.parent)
        dirs[key]=dirs.get(key, 0)+1

Which can easily be used for a total as well:

fc=sum(dirs.values())

Or,

print(f'{sum(dirs.values())} files in {sum(1 for _ in dirs.keys())} directories')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ksai
Solution 2 tdelaney
Solution 3