在Python中如何将下面的对象写入csv文件,以后我可以手动导入Excel?
from collections import OrderedDict
import csv
data = OrderedDict([(('2016-11-01', 'USD'), ['ECB News', 'FED News']),
(('2016-11-02', 'EUR'), ['Brexit News']),
(('2016-11-03', 'USD'), ['Yellen Speaking'])])
with open('output.csv', 'wb') as output:
writer = csv.writer(output)
for each in data:
for key, value in each.iteritems(): #<<<<<----- error here
writer.writerow([key, value])
错误:
for key, value in each.iteritems():
AttributeError: 'tuple' object has no attribute 'iteritems'
需要CSV输出:
2016-11-01;USD;ECB News,FED News
2016-11-02;EUR;Brexit News
2016-11-03;USD;Yellen Speaking
答案 0 :(得分:1)
each
是data
字典中的关键字,它正确地说是一个元组。你可能只是把iteritems()
放在了错误的地方:
from io import StringIO
with StringIO() as output:
writer = csv.writer(output, delimiter=';')
for k, v in data.iteritems():
writer.writerow(list(k)+[','.join(v)])
print(output.getvalue())
输出:
2016-11-01;USD;ECB News,FED News
2016-11-02;EUR;Brexit News
2016-11-03;USD;Yellen Speaking
您可以替换:
for k, v in data.iteritems():
writer.writerow(list(k)+[','.join(v)])
使用:
writer.writerows(list(k)+[','.join(v)] for k, v in data.iteritems())