本文介绍了与os.walk的嵌套列表理解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
试图枚举某个目录中的所有文件(在Linux中为"find.",在Windows中为"dir/s/b").
Trying to enumerate all files in a certain directory (like 'find .' in Linux, or 'dir /s /b' in Windows).
我想出了以下嵌套列表理解:
I came up with the following nested list comprehension:
from os import walk
from os.path import join
root = r'c:\windows' #choose any folder here
allfiles = [join(root,f) for f in files for root,dirs,files in walk(root)]
不幸的是,对于最后一个表达式,我得到:
Unfortunately, for the last expression, I'm getting:
NameError: name 'files' is not defined
与此问题相关,该问题(尽管有效)我无法理解嵌套列表理解的语法.
Related to this question, which (although working) I can't understand the syntax of the nested list comprehension.
推荐答案
您需要反转嵌套;
allfiles = [join(root,f) for root,dirs,files in walk(root) for f in files]
请参见列表理解文档:
换句话说,由于您基本上想要道德上等同于:
In other words, since you basically want the moral equivalent of:
allfiles = []
for root, dirs, files in walk(root):
for f in files:
allfiles.append(f)
您的列表理解应遵循相同的顺序.
your list comprehension should follow the same ordering.
这篇关于与os.walk的嵌套列表理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!