Python dict转csv

时间:2019-10-03 06:54:23

标签: python

我编写了一个脚本来查找目录中所有图像的图像大小和纵横比以及它们相应的文件路径,我想将dict值打印到csv文件中,并包含以下标题的宽度,高度,纵横比和文件路径

import os
import json
from PIL import Image

folder_images = "/home/user/Desktop/images"
size_images = dict()
def yocd(a,b): 
    if(b==0): 
        return a 
    else: 
        return yocd(b,a%b) 
for dirpath, _, filenames in os.walk(folder_images):
        for path_image in filenames:
            if path_image.endswith(".png") or path_image.endswith('.jpg')  or path_image.endswith('.JPG') or path_image.endswith('.jpeg'):
                image = os.path.abspath(os.path.join(dirpath, path_image))
                """ ImageFile.LOAD_TRUNCATED_IMAGES = True """
                try:
                    with Image.open(image) as img:
                        img.LOAD_TRUNCATED_IMAGES = True
                        img.verify()
                        print('Valid image')
                except Exception:
                        print('Invalid image')
                        img = False
                if img is not False:
                    width, heigth = img.size
                    divisor = yocd(width, heigth)
                    w = str(int(width / divisor))
                    h = str(int(heigth / divisor))
                    aspectratio = w+':'+h
                    size_images[image] = {'width': width, 'heigth': heigth,'aspect-ratio':aspectratio,'filepath': image}
for k, v in size_images.items():
    print(k, '-->', v) 
with open('/home/user/Documents/imagesize.txt', 'w') as file:
     file.write(json.dumps(size_images))```


2 个答案:

答案 0 :(得分:0)

您可以直接将{(1)} dict添加到pandas.DataFrame中。然后,DataFrame具有一个.to_csv()函数。

以下是文档:

答案 1 :(得分:0)

没有依赖性(但是您可能需要调整格式)

csv_sep = ';' # choose here wich field separatar you want
with open('your_csv', 'w') as f:
    # header
    f.write("width"+csv_sep"+height"+csv_sep"+aspect-ratio"+csv_sep+"filepath\n")
    # data
    for img in size_images:
        fields = [img['width'], img['height'], img['aspect-ratio'], img['filepath']]
        f.write(csv_sep.join(fields)+'\n')