Pau*_*tas 28 python os.walk non-recursive
我正在寻找一种方法来进行非递归os.walk()步行,就像os.listdir()工作一样.但我需要以同样的方式os.walk()返回.任何的想法?
先感谢您.
Ign*_*ams 33
next(os.walk(...))
Run Code Online (Sandbox Code Playgroud)
Ale*_*ecz 18
break在循环文件名后面添加一个:
for root, dirs, filenames in os.walk(workdir):
for fileName in filenames:
print (fileName)
break #prevent descending into subfolders
Run Code Online (Sandbox Code Playgroud)
这是有效的,因为(默认情况下)os.walk首先列出所请求文件夹中的文件,然后进入子文件夹.
我的更多参数化解决方案是这样的:
for root, dirs, files in os.walk(path):
if not recursive:
while len(dirs) > 0:
dirs.pop()
//some fency code here using generated list
Run Code Online (Sandbox Code Playgroud)
编辑:修复,if/while issue.谢谢,@ Dirk van Oosterbosch:}