我正在寻找一种像os.listdir()
一样进行非递归os.walk()
遍历的方法。但我需要以与os.walk()
返回相同的方式返回。有什么想法吗?
提前谢谢你。
发布于 2010-11-07 20:00:45
next(os.walk(...))
发布于 2016-11-01 03:46:30
在for循环文件名后添加break
:
for root, dirs, filenames in os.walk(workdir):
for fileName in filenames:
print (fileName)
break #prevent descending into subfolders
这是因为(默认情况下) os.walk
首先列出请求的文件夹中的文件,然后进入子文件夹。
发布于 2013-01-30 23:51:29
我的更参数化的解决方案是:
for root, dirs, files in os.walk(path):
if not recursive:
while len(dirs) > 0:
dirs.pop()
//some fency code here using generated list
编辑:修复,如果/当问题。谢谢,@Dirk van Oosterbosch :}
https://stackoverflow.com/questions/4117588
复制相似问题