Non-recursive os.walk()
我正在寻找一种方法来执行非递归的
提前谢谢。
1  | next(os.walk(...))  | 
在循环的文件名后面添加一个
1 2 3 4  | for root, dirs, filenames in os.walk(workdir): for fileName in filenames: print (fileName) break #prevent decending into subfolders  | 
这是因为(默认情况下)
我的一个更为参数化的解决方案是:
1 2 3 4 5 6  | for root, dirs, files in os.walk(path):   if not recursive: while len(dirs) > 0: dirs.pop() //some fency code here using generated list  | 
编辑:修复,if/while问题。谢谢,@dirk van oosterbosch:
Kamiccolo的意思更符合这一点:
1 2 3 4  | for str_dirname, lst_subdirs, lst_files in os.walk(str_path): if not bol_recursive: while len(lst_subdirs) > 0: lst_subdirs.pop()  |