Non-recursive os.walk()
Asked Answered
S

6

52

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.

Syngamy answered 7/11, 2010 at 11:57 Comment(0)
C
43
next(os.walk(...))
Circinus answered 7/11, 2010 at 12:0 Comment(4)
More simple than I could think... Thank you!Syngamy
what does next do?Filet
Then you have to have two forms of the loop if you want to make the recursion optional :(Neuroglia
would be more helpful with a 3 line example, this is just a hint in this format. -1Chiliad
J
64

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.

Jarredjarrell answered 31/10, 2016 at 19:46 Comment(1)
I feel this ought to be the accepted answer. So very simple and accurate.Precautionary
C
43
next(os.walk(...))
Circinus answered 7/11, 2010 at 12:0 Comment(4)
More simple than I could think... Thank you!Syngamy
what does next do?Filet
Then you have to have two forms of the loop if you want to make the recursion optional :(Neuroglia
would be more helpful with a 3 line example, this is just a hint in this format. -1Chiliad
N
6

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

Nieman answered 30/1, 2013 at 15:51 Comment(2)
This only works if there is one subdirectory. For multiple subdirectories use while len(dirs) > 0 instead of if.Waligore
@DirkvanOosterbosch: or even simpler: just if not recursive: break Unrelated: you could use del dirs[:] instead of while dirs: dirs.pop().Autry
C
1

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()
Castleman answered 15/11, 2013 at 17:7 Comment(0)
G
1

Empty the directories list

for r, dirs, f in os.walk('/tmp/d'):
    del dirs[:]
    print(f)
Gargan answered 7/4, 2021 at 12:32 Comment(0)
W
0

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
Wondawonder answered 3/12, 2021 at 16:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.