Python-如何筛选文件列表并仅返回包含特定扩展名的值?

时间:2020-07-28 21:06:33

标签: python

使用python 3.7,我需要像显示的文件一样列出文件的列表example_list = ["example1.jar","example2.txt",并创建一个仅返回以“ .jar”结尾的文件名的函数。是否有简短的方法完成这项工作?

5 个答案:

答案 0 :(得分:3)

使用列表理解:

[name for name in example_list if name.endswith(".jar")]

答案 1 :(得分:2)

这可能是过分的,但是您可以使用pathlib.PurePath,它还提供了提供完整路径的功能:

from pathlib import PurePath

example_list = ["example1.jar","example2.txt"]
paths = map(PurePath, example_list)

names = [p.name for p in paths if p.suffix == '.jar']

结果:

>>> names
['example1.jar']

答案 2 :(得分:1)

还有另一种方法:

list(filter(lambda item: item.endswith('.jar'), ["example1.jar","example2.txt", "example3.jar"]) 

注意:由于函数调用的一些开销,因此此实现将比使用列表理解慢。

答案 3 :(得分:0)

如果文件名是列表中的字符串,则可以将list comprehension与功能endswith()一起使用:

files_filtered = [x for x in example_list if x.endswith('.jar')]

这将返回:

['example1.jar']

答案 4 :(得分:0)

创建一个函数并使用split方法和列表理解

def filter_files(files_list: list) -> list:
    return [file for file in files_list if file.split('.')[1] == 'jar']

print(filter_files(["example1.jar","example2.txt"]))
>>> ['example1.jar']