What is the Python way to walk a directory tree?

Mike picture Mike · Jul 10, 2011 · Viewed 44.5k times · Source

I feel that assigning files, and folders and doing the += [item] part is a bit hackish. Any suggestions? I'm using Python 3.2

from os import *
from os.path import *

def dir_contents(path):
    contents = listdir(path)
    files = []
    folders = []
    for i, item in enumerate(contents):
        if isfile(contents[i]):
            files += [item]
        elif isdir(contents[i]):
            folders += [item]
    return files, folders

Answer

Sanjay T. Sharma picture Sanjay T. Sharma · Jul 10, 2011

Take a look at the os.walk function which returns the path along with the directories and files it contains. That should considerably shorten your solution.