我很难理解如何将字典列表写入 csv,其中我的所有值都在不同的列中。 SO 上与此类似的问题并没有帮助我理解。我一直在使用 DictWriter,但无法弄清楚如何在没有错误“字段 x 不在字段名中”的情况下输入 dict.values()。
.....
dicts = [
{'sku': 'xxxx1', 'model': '1234-56K', 'price': '$xxx.xx', 'name': 'item_name_here', 'stock': 'True'},
{'sku': 'xxxx2', 'model': '1234-56K', 'price': '$xxx.xx', 'name': 'item_name_here', 'stock': 'False'}
]
csv_file = open('file.csv','wb')
fieldnames = ('name', 'price', 'stock', 'model', 'sku')
csvwriter = csv.DictWriter(csv_file, fieldnames, extrasaction='raise', dialect='excel')
csvwriter.writeheader()
csvwriter.writerows(dicts)
return csv_file
.....
这会在单个列中返回我的值,但是当我遍历列表中字典的值时,它只是将所有值(作为字符串)拆分为“s、t、r、i、n、g”,仍然将它们放入第一列。
请您参考如下方法:
来自 csv.DictWriter() 的文档:
If the dictionary passed to the writerow() method contains a key not found in fieldnames, the optional extrasaction parameter indicates what action to take. If it is set to 'raise' a ValueError is raised. If it is set to 'ignore', extra values in the dictionary are ignored.
如果这是您遇到的错误,请尝试:
csv.DictWriter(csv_file, fieldnames, extrasaction='ignore', dialect='excel')
