簡體   English   中英

Python - 嘗試將元數據打印到表中

[英]Python - Trying to print metadata into a table

我有一個 python 腳本,它現在可以獲取照片的元數據並將其打印到一個文本文件中,但是我想將它打印到一個看起來像這樣的表中

| Filename | DPI | Height | Width | Format | Mode | Frames |

這是腳本:

from PIL import Image
from PIL.ExifTags import TAGS
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"

newfile = newfile = open('meta.txt', 'w')

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

    for label, value in info_dict.items():
        #print(f"{label:25}: {value}")
        newfile.write(f"{label:25}: {value}"+'\n')

當前輸出如下所示:

Filename                 : C:\Users\Eddie\Pictures\pics\X01CJ0035.JPG
Image DPI                : (72.0, 72.0)
Image Height             : 400
Image Width              : 600
Image Format             : JPEG
Image Mode               : RGB
Frames in Image          : 1

我想以某種方式將這些數據打印到表格中,而不必將所有內容都放入表格中,我不知道該怎么做。

任何幫助都會很棒!

您可以更改第二個for循環以水平打印:

newfile.write("Filename   |  Image DPI    | ...\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 += " |\n"  
    #print(line)
    newfile.write(line)

嘗試從您擁有的 dict 創建一個 pandas 數據框。 您可以稍后為每個字典添加行。 不要忘記導入熊貓。

供參考: https ://pandas.pydata.org/docs/reference/api/pandas.DataFrame.from_dict.html

暫無
暫無

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

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