How do I get number of files in a particular directory.

Stefan Schwarzer sschwarzer at sschwarzer.net
Fri Aug 13 05:30:37 EDT 2010


On 2010-08-13 11:18, blur959 wrote:
> import os
> 
> directory = raw_input("Please input file directory. \n\n")
> s = raw_input("Please input a name to replace. \n\n")
> ext = raw_input("input file ext")
> 
> for files in os.listdir(directory):
>     if ext in files:
>         file_number = len(files)
>         print file_number
> 
> 
> The result is:
> 13
> 13
> 13
> 6
> 15
> 8
> 10
> 10
> 8
> 7
> 5
> 
> where the result should be just 11. Can anyone help me? Thanks.

`os.listdir` returns a list of names. What you named
`files` should actually be `filename`. What you got
printed in the loop are the lengths of each filename.

Stefan



More information about the Python-list mailing list