簡體   English   中英

Python - KeyError:'dpi'

[英]Python - KeyError: 'dpi'

我有一個 python 腳本,它列出了目錄中照片的元數據。 它可以工作,但不能完全正常工作。 當它運行時,我可以從 ~250 個文件中獲取數據,然后出現錯誤

這是錯誤:

  File "c:\Users\edward\OneDrive - ISC Industries\Summer Intern 2022\Scripts\metadata.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:\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')

謝謝

您可以使用tryexcept只需重用您的代碼:

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')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM