Non-recursive os.walk()

Question:

I’m looking for a way to do a non-recursive os.walk() walk, just like os.listdir() works. But I need to return in the same way the os.walk() returns. Any idea?

Thank you in advance.

Asked By: user222758

||

Answers:

next(os.walk(...))

My a bit more parametrised solution would be this:

for root, dirs, files in os.walk(path):  
    if not recursive:  
        while len(dirs) > 0:  
            dirs.pop()  

    //some fancy code here using generated list

Edit: fixes, if/while issue. Thanks, @Dirk van Oosterbosch :}

Answered By: Kamiccolo

Well what Kamiccolo meant was more in line with this:

for str_dirname, lst_subdirs, lst_files in os.walk(str_path):
    if not bol_recursive:
          while len(lst_subdirs) > 0:
              lst_subdirs.pop()
Answered By: Sanders

Add a break after the filenames for loop:

for root, dirs, filenames in os.walk(workdir):
    for fileName in filenames:
        print (fileName)
    break   #prevent descending into subfolders

This works because (by default) os.walk first lists the files in the requested folder and then goes into subfolders.

Answered By: Alecz

Empty the directories list

for r, dirs, f in os.walk('/tmp/d'):
    del dirs[:]
    print(f)
Answered By: gerardw

Flexible Function for counting files:

You can set recursive searching and what types you want to look for. The default argument: file_types=("", ) looks for any file. The argument file_types=(".csv",".txt") would search for csv and txt files.

from os import walk as os_walk

def count_files(path, recurse=True, file_types = ("",)):
    file_count = 0
    iterator = os_walk(path) if recurse else ((next(os_walk(path))), )
    for _, _, file_names in iterator:
        for file_name in file_names:
            file_count += 1 if file_name.endswith(file_types) else 0
    return file_count
Answered By: Leon Blum
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.