Python打印文件名时输出完整路径而非仅文件名的解决方法
问题描述
编写Python脚本批量提取图片元数据时,文件名字段输出完整绝对路径,不符合仅输出单独文件名的需求:
- 当前输出格式:
C:\Users\edward\OneDrive\Pics\X00DL0027.jpg
- 期望输出格式:
X00DL0027.jpg
原问题附初始脚本如下:
import json from PIL import Image from PIL.ExifTags import TAGS import os import os.path import PIL from pandas import json_normalize PIL.Image.MAX_IMAGE_PIXELS = 384000000 rootdir = r"C:\Users\edward\OneDrive\Pics" newfile = newfile = open('meta.txt', 'w') newfile.write("Filename | Image DPI | Image Height | Image Width | Image Format | Image Mode | Image Frames |\n") for file in os.listdir(rootdir): # read the image data using PIL image = Image.open(os.path.join(rootdir, file)) # extract other basic metadata info_dict = { "Filename": image.filename, "Image DPI": image.info['dpi'], "Image Height": image.height, "Image Width": image.width, "Image Format": image.format, "Image Mode": image.mode, "Frames in Image": getattr(image, "n_frames", 1) } line = "" for label, value in info_dict.items(): line += f"|{str(value):<30} " line += " |" newfile.write(line + '\n')
解决方案
问题根因
- PIL的
Image对象的filename属性会直接返回传入Image.open()的完整路径字符串,不会自动截取末尾的文件名部分 - 原脚本存在缩进错误:元数据提取、内容写入的逻辑全部在
for循环外部,实际运行只会处理遍历到的最后一个文件,无法批量处理目录下所有图片
修改方法
- 构建
info_dict时,用标准库os.path的basename()方法处理image.filename,该方法会自动从完整路径中拆分出末尾的单独文件名,兼容Windows路径格式 - 修正
for循环缩进,将图片加载、元数据解析、行写入的逻辑全部移入循环块内,保证遍历到的每个文件都能被处理 - 可顺手修正原脚本重复赋值、未使用冗余导入、无异常捕获易报错、文件句柄未正常关闭的问题,提升脚本稳定性
修改后可直接运行的代码
from PIL import Image import os import PIL PIL.Image.MAX_IMAGE_PIXELS = 384000000 rootdir = r"C:\Users\edward\OneDrive\Pics" # 用上下文管理器自动处理文件关闭 with open('meta.txt', 'w', encoding='utf-8') as newfile: newfile.write("Filename | Image DPI | Image Height | Image Width | Image Format | Image Mode | Image Frames |\n") for file in os.listdir(rootdir): file_path = os.path.join(rootdir, file) # 跳过子目录,只处理文件 if not os.path.isfile(file_path): continue try: image = Image.open(file_path) info_dict = { # 核心修改:用os.path.basename截取单独文件名 "Filename": os.path.basename(image.filename), "Image DPI": image.info.get('dpi', 'N/A'), "Image Height": image.height, "Image Width": image.width, "Image Format": image.format, "Image Mode": image.mode, "Frames in Image": getattr(image, "n_frames", 1) } line = "" for label, value in info_dict.items(): line += f"|{str(value):<30} " line += " |" newfile.write(line + '\n') except Exception as e: # 跳过无法解析为图片的文件 print(f"跳过文件{file},解析失败:{str(e)}")
核心需求仅需把原代码中"Filename": image.filename替换为"Filename": os.path.basename(image.filename)即可实现,其余修改为修复原脚本的运行逻辑缺陷。
内容的提问来源于stack exchange,提问作者Eddiex045
相关产品推荐
相关产品推荐

