Count Files in a Directory

Jay Dorsey jay at jaydorsey.com
Sun Dec 21 19:29:33 EST 2003


On Sun, Dec 21, 2003 at 03:45:31PM -0800, hokiegal99 wrote:
> I'm trying to count the number of files within a directory, but I
> don't really understand how to go about it. This code:
> 

Do you want the total number of files under one directory, or
the number of files under each directory?

> for root, dirs, files in os.walk(path):
>    for fname in files:
>       x = str.count(fname)
>       print x
>
> Produces this error:
> 
> TypeError: count() takes at least 1 argument (0 given)

str.count() is a string method used to obtain the number of 
occurences of a substring in a string (try help(str.count))

>>> n = "this is a test"
>>> n.count("test")
1

> 
> for root, dirs, files in os.walk(path):
>    for fname in files:
>       x = list.count(files)
>       print x
> 
> TypeError: count() takes exactly one argument (0 given)
> 
> Also wondered why the inconsistency in error messages (numeric 1 vs.
> one)??? Using 2.3.0
Similar problem here, for a list method ( try help(list.count)).

>>> n = ["test", "blah", "bleh"]
>>> n.count("test")
1

In your example, fname would be an individual file name within a 
directory list of files (in your example, the variable files).

What you probably want is len(), not count().  

If you want the number of files in each directory try:

>>> for root, dirs, files in os.walk(path):
... 	print len(files)

Or, for the total number of files:

>>> filecount = 0
>>> for root, dirs, files in os.walk(path):
...		filecount += len(files)	
>>> print filecount

hth

-- 
Jay Dorsey
jay at jaydorsey dot com





More information about the Python-list mailing list