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.
next(os.walk(...))
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.
Kamiccolo
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()
来源:https://stackoverflow.com/questions/4117588/non-recursive-os-walk