DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

List Files Recursivly With Python

  • submit to reddit
import os
import stat

def walktree (top = ".", depthfirst = True):
    names = os.listdir(top)
    if not depthfirst:
        yield top, names
    for name in names:
            st = os.lstat(os.path.join(top, name))
        except os.error:
        if stat.S_ISDIR(st.st_mode):
            for (newtop, children) in walktree (os.path.join(top, name), depthfirst):
                yield newtop, children
    if depthfirst:
        yield top, names

for (basepath, children) in walktree("/home",False):
    for child in children:
        print os.path.join(basepath, child)