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

Dave Angel davea at ieee.org
Fri Aug 13 08:15:29 EDT 2010


blur959 wrote:
> On Aug 13, 6:09 pm, Peter Otten <__pete... at web.de> wrote:
>   
>> blur959 wrote:
>>     
>>> Hi, I tried that, but it doesn't seem to work. My file directory has
>>> many different files extensions, and I want it to return me a number
>>> based on the number of files with similar files extensions. But when I
>>> tried running it, I get many weird numbers. Below is my code i had so
>>> far and the result.
>>>       
>> Use glob.glob() instead of os.listdir() if you are only interested in files
>> with a specific extension:
>>
>>     
>>>>> import glob
>>>>> len(glob.glob("*.py"))
>>>>>           
>> 42
>>
>> Peter
>>     
>
>
> Hi, I want to make it such that the user inputs a file extension and
> it prints the number of similar file extensions out.
> I tried doing this:
>
> directory =aw_input("input file directory")
> ext =aw_input("input file ext")
>
> file_list =en(glob.glob(ext))
> print file_list
>
>
> And my result was this:
> 0
> which it is suppose to be 11
>
> May I know why? And how do I specify which directory it is searching
> the files extension from? I want the user to specify a directory and
> it searches the particular directory for the particular file
> extensions and prints the number out.
> Hope you guys could help.
>
> Thanks
>
>   
Glob doesn't do much useful unless there's a wildcard.  And as you point 
out, it also needs the directory.  You want to pass it something like
      mydirect/*.txt

In your case, you might construct that with something like
      os.path.join(directory, "*." + ext)

DaveA




More information about the Python-list mailing list