简体   繁体   中英

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM