如何仅返回具有特定文件类型的文件?

时间:2018-09-26 18:53:54

标签: python

这是我的代码:

import os

def read_file(path):
    name_file = os.listdir(path)
    return name_file

path = "/home/ich/Schreibtisch/fotki"
print(read_file(path)) 

这仅返回列表中文件夹中的所有文件。但我希望他们以".jpg"结尾。文件夹中有很多文件(.jpg.txt,...),但我只希望这些.jpg文件。

1 个答案:

答案 0 :(得分:2)

使用os.listdir.endswith

import os

path = "/home/ich/Schreibtisch/fotki"

for file in os.listdir(path):
    if file.endswith(".jpg"):
        print(os.path.join(path, file))