[Tutor] directory recursion

Christopher Arndt chris.arndt at web.de
Fri Sep 9 21:49:56 CEST 2005


Rob Andrews schrieb:
> I should already know this, and probably once did, but have never had
> a real world use for it until now.
> 
> What's a nice, clean way to recursively scan through directories with
> an arbitrary number of subdirectories?

os.walk() is you friend! (Don't use os.path.walk() anymore)

"Off the top of my head":

for dir, dirnames, filenames in os.walk(topdir):
    for dir in dirnames:
        do_something_with_subdir(os.path.join(dir, dirname)
    for file in filenames:
        do_something_with_file(os.path.join(dir, filename)

HTH, Chris



More information about the Tutor mailing list