Non-recursive 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 :}


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.


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()

next(os.walk(...))