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.

Was it helpful?

Solution

next(os.walk(...))

OTHER TIPS

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.

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 fency code here using generated list

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

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()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top