49

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.

Paulo Freitas
  • 13,194
  • 14
  • 74
  • 96

6 Answers6

58

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.

Alecz
  • 1,951
  • 1
  • 19
  • 18
44
next(os.walk(...))
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
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 :}

gerardw
  • 5,822
  • 46
  • 39
Kamiccolo
  • 7,758
  • 3
  • 34
  • 47
  • 4
    This only works if there is **one** subdirectory. For multiple subdirectories use `while len(dirs) > 0` instead of `if`. – Dirk van Oosterbosch Apr 23 '13 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 05 '16 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()
Sanders
  • 11
  • 1
1

Empty the directories list

for r, dirs, f in os.walk('/tmp/d'):
    del dirs[:]
    print(f)
gerardw
  • 5,822
  • 46
  • 39
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
Leon Blum
  • 21
  • 3