Python dict to csv



我编写了一个脚本来查找目录中所有图像的图像大小和纵横比及其相应的文件路径,我想将字典值打印到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))```

您可以将(正确构造的(dict直接添加到pandas.DataFrame。 然后,数据帧具有.to_csv()功能。

以下是文档:

  • 熊猫:创建数据帧
  • 熊猫:写入 CSV

没有依赖关系(但您可能需要调整格式(

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+"filepathn")
# data
for img in size_images:
fields = [img['width'], img['height'], img['aspect-ratio'], img['filepath']]
f.write(csv_sep.join(fields)+'n')

最新更新