51

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.

6 Answers 6

62

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.

1
  • 8
    I feel this ought to be the accepted answer. So very simple and accurate. Jun 17, 2019 at 21:59
43
next(os.walk(...))
4
  • More simple than I could think... Thank you! Nov 7, 2010 at 12:14
  • 20
    what does next do?
    – tremendows
    Sep 7, 2018 at 17:34
  • 4
    Then you have to have two forms of the loop if you want to make the recursion optional :(
    – CpILL
    Nov 12, 2018 at 13:02
  • 2
    would be more helpful with a 3 line example, this is just a hint in this format. -1
    – Avi
    Sep 28 at 6:38
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 :}

2
  • 4
    This only works if there is one subdirectory. For multiple subdirectories use while len(dirs) > 0 instead of if. Apr 23, 2013 at 19:35
  • @DirkvanOosterbosch: or even simpler: just if not recursive: break Unrelated: you could use del dirs[:] instead of while dirs: dirs.pop().
    – jfs
    Jul 5, 2016 at 18:02
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()
1

Empty the directories list

for r, dirs, f in os.walk('/tmp/d'):
    del dirs[:]
    print(f)
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.