Count Files in a Directory

Anand Pillai pythonguy at Hotpop.com
Tue Dec 23 01:03:26 EST 2003


os.walk() does not follow symlinks to avoid infinite recursions.
This could be the reason for the difference in reported count.

Qouting from python docs for 2.3,

"""Note: On systems that support symbolic links, links to
subdirectories appear in dirnames lists, but walk() will not visit
them (infinite loops are hard to avoid when following symbolic links).
To visit linked directories, you can identify them with
os.path.islink(path), and invoke walk(path) on each directly."""

You can do something like this.

dir_count, file_count = 0, 0

#untested code!
def dircount(path):

    for root, dirs, files in os.walk(path):
        dir_count += len(dirs)
        file_count += len(files)
        if os.path.islink(path) and os.path.isdir(path):
            dircount(path)
   
HTH.

-Anand

Peter Otten <__peter__ at web.de> wrote in message news:<bs7g28$ogm$02$1 at news.t-online.com>...
> hokieghal99 wrote:
> 
> >     The os thinks there are 12,204 objects in the path while Python
> > thinks there are 12,205 objects.
> 
> If it's always one more directory then it could be the initial directory
> setpath (ugly name, by the way) that is counted by the os but not by your
> function. To fix it, you could initialize 
> 
> dir_count = 1 # instead of 0
> 
> Peter




More information about the Python-list mailing list