Count Files in a Directory

hokieghal99 hokiegal99 at hotmail.com
Mon Dec 22 11:44:46 EST 2003


Peter Otten wrote:
> 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

Wow!!! What an obvious error. I've drank too much coffee this morning. 
We would have caught something this bad in testing. Thanks for the 
help... you've saved me a bit of embarassment.





More information about the Python-list mailing list