Python将PIL提取的图片元数据输出为指定格式表格的实现方法
实现方案
你只需要调整输出逻辑,按照Markdown表格的固定结构先写表头、分隔行,再逐张图片写入对应行数据即可,修改后的完整可运行代码如下,同时补充了异常兼容、资源释放的优化,避免脚本运行崩溃:
from PIL import Image import os import os.path import PIL PIL.Image.MAX_IMAGE_PIXELS = 384000000 rootdir = r"C:\Users\edward\OneDrive - ISC Industries\Summer Intern 2022\Suspensia Pictures" # 上下文管理器自动处理文件关闭,无需手动调用close with open('meta.txt', 'w', encoding='utf-8') as newfile: # 写入Markdown表格固定表头 newfile.write("| Filename | DPI | Height | Width | Format | Mode | Frames |\n") # 写入表头与内容的分隔行,符合Markdown表格语法要求 newfile.write("| --- | --- | --- | --- | --- | --- | --- |\n") for file in os.listdir(rootdir): file_path = os.path.join(rootdir, file) # 跳过子目录,仅处理文件 if not os.path.isfile(file_path): continue try: with Image.open(file_path) as image: # 提取字段,按需做格式适配 # 若需要保留文件全路径,去掉os.path.basename()直接赋值image.filename即可 filename = os.path.basename(image.filename) # 兼容无DPI信息的图片,格式化DPI元组提升可读性 dpi = image.info.get('dpi', ('Unknown', 'Unknown')) dpi_display = f"{round(dpi[0])}" if dpi[0] == dpi[1] else f"{round(dpi[0])}x{round(dpi[1])}" height = image.height width = image.width img_format = image.format mode = image.mode frames = getattr(image, "n_frames", 1) # 拼接当前图片对应的表格行写入文件 row = f"| {filename} | {dpi_display} | {height} | {width} | {img_format} | {mode} | {frames} |\n" newfile.write(row) except Exception as e: # 遇到非图片、损坏文件直接跳过,打印提示避免脚本中断 print(f"跳过无法处理的文件 {file}: {str(e)}") continue
关键改动说明
- 输出顺序调整:不再逐字段换行写键值对,而是先写统一表头、分隔行,每张图片对应一行表格数据,完全匹配你需要的输出格式
- DPI字段优化:原脚本直接输出浮点元组
(72.0, 72.0)可读性差,修改后水平/垂直DPI一致时显示整数值,不一致时显示为水平值x垂直值格式,无DPI信息时显示Unknown - 鲁棒性提升:增加了子目录过滤、非图片/损坏文件的异常捕获,不会因为目录下存在非图片文件导致脚本运行中途崩溃
- 资源管理优化:用
with语句管理文件、图片对象的生命周期,不需要手动调用close方法,避免资源泄漏
运行后生成的meta.txt内容样例如下:
| Filename | DPI | Height | Width | Format | Mode | Frames | | --- | --- | --- | --- | --- | --- | --- | | X01CJ0035.JPG | 72 | 400 | 600 | JPEG | RGB | 1 | | product.png | 96 | 1200 | 1200 | PNG | RGBA | 1 | | animate.gif | 72 | 480 | 480 | GIF | P | 24 |
内容的提问来源于stack exchange,提问作者Eddiex045
相关产品推荐
相关产品推荐

