Count Files in a Directory

Anand Pillai pythonguy at Hotpop.com
Mon Dec 22 03:23:50 EST 2003


If you are using Python 2.3, the new os.walk() function
is a better and faster choice.

Here is a sample code for counting files & sub-dirs recursively.
        
---------<snip>------<snip>-------------------

# dircount.py 
import os

dir_count, file_count=0, 0
for root, dirs, files in os.walk('.'):
    dir_count += len(dirs)
    file_count += len(files)

print 'Found', dir_count, 'sub-directories in cwd'
print 'Found', file_count, 'files in cwd'
print 'Found', dir_count + file_count, 'files & sub-directories in cwd'
---------<snip>------<snip>-------------------

-Anand

Jay Dorsey <jay at jaydorsey.com> wrote in message news:<mailman.20.1072053448.684.python-list at python.org>...
> 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




More information about the Python-list mailing list