Count Files in a Directory

John Roth newsgroups at jhrothjr.com
Mon Dec 22 01:15:42 CET 2003


"hokiegal99" <hokiegal99 at hotmail.com> wrote in message
news:93f5c5e9.0312211545.363b91a6 at posting.google.com...
> 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:
>
> for root, dirs, files in os.walk(path):
>    for fname in files:
>       x = str.count(fname)
>       print x

I'm not sure why you're trying to use the str(ing)
module.

(untested)
for root, dirs, files in os.walk(path):
    print "files in '%s': '%s'" % (root, len(files))

This should give you a list of the directories
under 'path,' with the number of files (not
directories!) in each one.

>
> Produces this error:
>
> TypeError: count() takes at least 1 argument (0 given)
>
> 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

One function (str.count) seems to have keyword arguments,
the other one doesn't. That's why the 'at least' versus the 'exactly.'
The two cases are processed slightly differently.

John Roth
>
> Thanks!!!






More information about the Python-list mailing list