How to count all the files from directory and subdirectories?

In this code, I am trying to find the length of all the files. When I print the f, it give me all the filenames from the directory and the subdiretories also but when I print the length it gave me this result.

4
7
7
3

I printed the length outside the loop also but it didn’t count the files in sudirectories.

Code

import os
path = '/home/runner/TestP1'

for root,d_names,f_names in os.walk(path):
  for f in f_names:
    length = len(f)
    print(length)

Answer

With for f in f_names: you’re iterating through the list of file names in the current root directory, so len(f) returns the length of each file name as a string, which is not what you want.

You can instead use the sum function with a generator expression that outputs the lengths of the lists of file names yielded by os.walk:

sum(len(filenames) for _, _, filenames in os.walk(path))

Leave a Reply

Your email address will not be published. Required fields are marked *