How do I get number of files in a particular directory.
Peter Otten
__peter__ at web.de
Fri Aug 13 07:21:58 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 = raw_input("input file directory")
> ext = raw_input("input file ext")
>
> file_list = len(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.
The part of the filename you don't care about has to be replaced with a "*":
import os
import glob
directory = raw_input("directory? ")
ext = raw_input("file extension? ")
pattern = os.path.join(directory, "*" + ext)
matching_files = glob.glob(pattern)
print len(matching_files), "matching files"
Note that you'll learn a lot more when you look up in the documentation how
the functions mentioned actually work instead of coming back here for every
tiny detail. I you don't feel ready yet to understand enough of the Python
documentation, go one step back and work your way through a tutorial or
introductory book. A starting point is here:
http://wiki.python.org/moin/BeginnersGuide/NonProgrammers
Peter
More information about the Python-list
mailing list