我有一个名为reader的csv.DictReader:
reader = csv.DictReader(csvfile())
for row in reader:
print(row)
给我以下输出:
{'field1': '23.10', 'field2': '48.70', 'entry_id': '18', 'created_at': '2017-09-10 09:21:43 UTC'}
{'field1': '23.10', 'field2': '48.30', 'entry_id': '19', 'created_at': '2017-09-10 10:20:35 UTC'}
{'field1': '23.00', 'field2': '48.50', 'entry_id': '20', 'created_at': '2017-09-10 11:19:29 UTC'}
我正在尝试将此DictReader元素写入csv文件。分隔符应为\t
,输出应如下所示:
created_at entry_id field1 field2
2017-09-10 09:21:43 UTC 18 23.10 48.70
2017-09-10 10:20:35 UTC 19 23.10 48.70
我尝试了以下内容:
with open(Write_File, 'w') as csv_file:
writer = csv.writer(csv_file,delimiter="\t", dialect="excel-tav")
for row in reader:
writer.writerow(row)
没有结果,我试图理解DictWriter模块,但我没有得到所需的输出。
答案 0 :(得分:2)
尝试使用csv.DictWriter
。
with open('output_file.csv', 'w', newline='') as csv_file:
fieldnames = ['created_at', 'entry_id', 'field1', 'field2']
writer = csv.DictWriter(csv_file, fieldnames, delimiter='\t')
writer.writeheader()
for row in reader:
writer.writerow(row)