【问题标题】:How do I save this piece of data to a csv file?如何将这段数据保存到 csv 文件?
【发布时间】:2019-08-26 23:12:10
【问题描述】:

我有一个看起来像这样的数据。如何将其保存到 csv 文件中?我正在考虑将其添加到另一个列表中,但我不确定这是否可行。我尝试使用下面链接中提出的问题的解决方案,但是 csv 文件只保存最后一张图像的坐标。

How do I write this piece of data to a csv file?

data = 
[{'box': [43, 37, 133, 168], 
 'confidence': 0.99, 
 'keypoints': {'left_eye': (78, 104), 
               'right_eye': (143, 99), 
               'nose': (110, 137), 
               'mouth_left': (82, 161), 
               'mouth_right': (147, 156)}}]

[{'box': [34, 33, 119, 161], 
  'confidence': 0.99,
  'keypoints': {'left_eye': (61, 104), 
                'right_eye': (116, 99), 
                'nose': (86, 133), 
                'mouth_left': (67, 161), 
                'mouth_right': (117, 156)}}]

这是我第一次问问题,如果不清楚,请原谅我!

我的预期输出是这样的:sample

【问题讨论】:

  • 欢迎来到 StackOverflow。请将链接数据直接发布到您的问题中,并避免使用链接、图像等间接信息。顺便说一句,您的 data 似乎不是一个有效的 python 对象。它应该是dict列表的列表?
  • 是的!它应该看起来像那样。

标签: python python-3.x csv export-to-csv


【解决方案1】:
import csv

fields = ['box', 'confidence', 'left_eye', 'right_eye', 'nose', 'mouth_left', 'mouth_right']

with open('output.csv', 'w') as file:
    writer = csv.DictWriter(file, fieldnames=fields)
    writer.writeheader()
    for item in data:
        writer.writerow({
            'box': item['box'],
            'confidence': item['confidence'],
            'left_eye': item['keypoints']['left_eye'],
            'right_eye': item['keypoints']['right_eye'],
            'nose': item['keypoints']['nose'],
            'mouth_left': item['keypoints']['mouth_left'],
            'mouth_right': item['keypoints']['mouth_right'],
        })

【讨论】:

    猜你喜欢
    • 2016-09-01
    • 2019-08-22
    • 1970-01-01
    • 2020-10-11
    • 1970-01-01
    • 2018-09-11
    • 2017-09-24
    • 2020-08-19
    • 2012-07-11
    相关资源
    最近更新 更多