You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何展示文件夹中前5张PNG图片且无需逐个指定文件名

Python实现指定文件夹前5张PNG图片批量展示

不需要提前知晓具体文件名,只需两步即可完成:先批量筛选文件夹内的PNG文件,再取前5个加载展示即可。

依赖安装

根据你常用的展示库选装其一即可:

  • 通用场景用Pillow:pip install pillow
  • 数据分析/Jupyter Notebook场景用matplotlib:pip install matplotlib

方案1:pathlib + Pillow 实现

pathlib是Python3.4+内置的路径处理库,无需额外安装,代码更简洁:

from pathlib import Path
from PIL import Image

# 替换为你的目标文件夹路径
target_dir = Path("./your_target_folder")

# 筛选所有png文件,忽略后缀大小写,按文件名排序后取前5个
png_files = sorted(
    [f for f in target_dir.iterdir() if f.suffix.lower() == ".png"],
    key=lambda x: x.name  # 可替换为x.stat().st_mtime按修改时间排序
)[:5]

# 逐个展示图片
for img_path in png_files:
    img = Image.open(img_path)
    img.show()

方案2:os + matplotlib 实现

适合需要把多张图片合并展示的场景:

import os
import matplotlib.pyplot as plt
from matplotlib.image import imread

# 替换为你的目标文件夹路径
target_dir = "./your_target_folder"

# 筛选png文件
all_files = os.listdir(target_dir)
png_files = sorted(
    [f for f in all_files if f.lower().endswith(".png")],
    key=lambda x: os.path.getmtime(os.path.join(target_dir, x))  # 按修改时间排序
)[:5]

# 把5张图排列在一行展示
plt.figure(figsize=(20, 4))
for idx, img_name in enumerate(png_files):
    img_path = os.path.join(target_dir, img_name)
    img = imread(img_path)
    plt.subplot(1, 5, idx+1)
    plt.imshow(img)
    plt.axis('off')
    plt.title(img_name)

plt.show()

注意事项

  • 代码中加入了后缀小写转换逻辑,可以兼容.PNG格式的大写后缀文件
  • 如果文件夹内PNG文件总数不足5个,代码会自动展示所有存在的PNG文件,不会报错
  • 可根据需求调整排序规则,支持按文件名、修改时间、创建时间等多种维度排序取前5个

内容的提问来源于stack exchange,提问作者Scheuchzeri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 16:06:04