题
我正在寻找一种非恢复性的方法 os.walk()
走路,就像 os.listdir()
作品。但是我需要以相同的方式返回 os.walk()
返回。任何的想法?
先感谢您。
解决方案
next(os.walk(...))
其他提示
添加一个 break
循环文件名之后:
for root, dirs, filenames in os.walk(workdir):
for fileName in filenames:
print (fileName)
break #prevent descending into subfolders
这是因为(默认情况下) 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
编辑:修复,如果/while问题。谢谢, @dirk van Oosterbosch :}
好吧,kamiccolo的含义更符合这一点:
for str_dirname, lst_subdirs, lst_files in os.walk(str_path):
if not bol_recursive:
while len(lst_subdirs) > 0:
lst_subdirs.pop()
不隶属于 StackOverflow