列表理解使用if条件获取特定类型的文件列表

时间:2015-02-23 19:54:27

标签: python list list-comprehension glob

大致遵循将列表推导与this solution中描述的if-else组合在一起的逻辑,我试图在父目录下获取具有特定扩展名的文件列表。

以下是代码的长形式:

mxd_list = []
for top_dir, dir_list, obj_list in os.walk(top_path):
    for obj in obj_list:
        if obj.endswith('.mxd'):
            mxd_list.append(os.path.join(top_dir, obj))

这是我目前尝试使用列表理解来巩固它。虽然它运行,但列表是空的。

for top_dir, dir_list, obj_list in os.walk(top_path):
    mxd_list = [os.path.join(top_dir, obj) for obj in obj_list if obj.endswith('.mxd')]

2 个答案:

答案 0 :(得分:4)

你很近。您需要附加到循环外的列表

mxd_list = []
for top_dir, dir_list, obj_list in os.walk(top_path):
    mxd_list.extend([os.path.join(top_dir, obj) for obj in obj_list if obj.endswith('.mxd')])

错误在于 - 在外部for循环的每次迭代中,list comp将仅生成特定于该迭代的列表,因此您需要extend每次迭代后生成的每个列表到外部变量mxd_list

注意 - [是冗余的,因为删除它们会使内容成为生成器表达式。这就是声明可以写成mxd_list.extend(os.path.join(top_dir, obj) for obj in obj_list if obj.endswith('.mxd'))

另一种方法 - 使用glob.iglob

As Padraic mentions

mxd_list = []
for top_dir, dir_list, obj_list in os.walk(top_path):
     mxd_list.extend(iglob(top_dir+"/*.mxd"))

这是一种更好的方法。但是不要忘记import模块,即from glob import iglob

答案 1 :(得分:0)

可以使用单个列表推导计算匹配文件的路径名列表

[os.path.join(d,f) for d,_,fl in os.walk(top) for f in fl if f.endswith(ext)]
相关问题