Count Files in a Directory

Peter Otten __peter__ at web.de
Mon Dec 22 11:28:49 EST 2003


hokieghal99 wrote:

> Thanks for the tip... this bit of code seems to work:
> 
> def fs_object_count(path):
>     file_count = 0
>     dir_count = 0
>     for root, dirs, files in os.walk(path):
>        for fname in files:
>           file_count += len(fname)
>        for dname in dirs:
>           dir_count += len(dname)
      # should return something, e. g:
      return dir_count, file_count
> fs_object_count()

No! You are calculating the total number of characters. Suppose path has two
subdirectories "alpha" and "beta". Your function would calculate a
dir_count of 9 instead of 2.

Instead of the inner for loops just add the length of the dirs list which is
equal to the number of subdirectories:

#untested
def fs_object_count(path):
    file_count = 0
    dir_count = 0
    for root, dirs, files in os.walk(path):
        file_count += len(files)
        dir_count += len(dirs)
    return dir_count, file_count
fs_object_count("/home/alone/II")

Peter







More information about the Python-list mailing list