codyc4321
codyc4321

Reputation: 9682

clean way to os.walk once python

I want to talk a few directories once, and just grab the info for one dir. Currently I use:

i = 0
for root, dirs, files in os.walk(home_path):
    if i >= 1:
        return 1
    i += 1
    for this_dir in dirs:
       do stuff

This is horribly tedious of course. When I want to walk the subdir under it, I do the same 5 lines, using j, etc...

What is the shortest way to grab all dirs and files underneath a single directory in python?

Upvotes: 2

Views: 747

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1125208

You can empty the dirs list and os.walk() won't recurse:

for root, dirs, files in os.walk(home_path):
    for dir in dirs:
        # do something with each directory
    dirs[:] = []  # clear directories.

Note the dirs[:] = slice assignment; we are replacing the elements in dirs (and not the list referred to by dirs) so that os.walk() will not process deleted directories.

This only works if you keep the topdown keyword argument to True, from the documentation of os.walk():

When topdown is True, the caller can modify the dirnames list in-place (perhaps using del or slice assignment), and walk() will only recurse into the subdirectories whose names remain in dirnames; this can be used to prune the search, impose a specific order of visiting, or even to inform walk() about directories the caller creates or renames before it resumes walk() again.

Alternatively, use os.listdir() and filter the names out into directories and files yourself:

dirs = []
files = []
for name in os.listdir(home_path):
    path = os.path.join(home_path, name)
    if os.isdir(path):
        dirs.append(name)
    else:
        files.append(name)

Upvotes: 6

Related Questions