python中csv.writer的tab'\ t'的分隔符

时间:2017-03-08 11:21:41

标签: python csv

我想将dict写入csv作为这种形式:

(column1)   (column2)
  aaa           1     
  bbb           2

但是当我在下面的代码中使用'\ t'作为分隔符时:

import csv

csv_filename = "test.csv"
dict = {'aaa': 1, 'bbb': 2} 
with open(csv_filename, 'wb') as f:
    writer = csv.writer(f, delimiter='\t')
    for key, value in dict.items():
        writer.writerow([key, value])

我无法获得所需的输出,而是创建的csv就像

(column1)   (column2)
  aaa1
  bbb2

1 个答案:

答案 0 :(得分:4)

您正在将输出转换为组合键和值的列表。请改用以下内容。

import csv

csv_filename = "test.csv"
dict = {'aaa': 1, 'bbb': 2} 
with open(csv_filename, 'wb') as f:
    writer = csv.DictWriter(f, delimiter='\t')
    writer.writerows(dict)