【问题标题】:Python - Trying to print metadata into a tablePython - 尝试将元数据打印到表中
【发布时间】:2022-07-15 22:20:38
【问题描述】:

我有一个 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

我想以某种方式将此数据打印到表格中,而不必将所有内容都打印到表格中,我不知道该怎么做。

任何帮助都会很棒!

【问题讨论】:

  • 也许试试这个:dict = json.loads(info_dict) df = json_normalize(dict) print(df)
  • 我会把它放在哪里
  • 您只想横向打印吗?
  • @PyMan 创建字典后

标签: python


【解决方案1】:

尝试从您拥有的 dict 创建一个 pandas 数据框。您可以稍后为每个字典添加行。不要忘记导入 pandas。

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

【讨论】:

    【解决方案2】:

    您可以更改第二个for 循环以水平打印:

        line = ""
        for label, value in info_dict.items():
            line += f"|{value:30} "  
        line += " |"  
        #print(line)
        newfile.write(line)
    

    【讨论】:

      猜你喜欢
      • 2018-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多