Each Answer to this Q is separated by one/two green lines.
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.
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()
Empty the directories list
for r, dirs, f in os.walk('/tmp/d'): del dirs[:] print(f)
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