我有一个python脚本,它列出了目录中照片的元数据。它工作,但它不是完全工作。当它运行时,我可以从~250个文件中获取数据,然后我得到一个错误
错误:
File "c:UsersedwardOneDrive - ISC IndustriesSummer Intern 2022Scriptsmetadata.py", line 22, in <module>
"Image DPI": image.info['dpi'],
KeyError: 'dpi'
我不知道为什么会这样,因为它适用于一些文件,但是有超过17000个文件,所以我想打印所有的数据。
以下是完整的脚本:
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:UsersedwardOneDrivePics"
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')
谢谢
您可以使用try
和except
,只需重用您的代码:
for file in os.listdir(rootdir):
try:
# read the image data using PIL
image = Image.open(os.path.join(rootdir,file))
# extract other basic metadata
info_dict = {
"Filename": os.path.basename(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')
except:
# read the image data using PIL
image = Image.open(os.path.join(rootdir,file))
# extract other basic metadata
info_dict = {
"Filename": os.path.basename(image.filename),
"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')