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

Nan*_*Nan 8 python csv

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

(column1)   (column2)
  aaa           1     
  bbb           2
Run Code Online (Sandbox Code Playgroud)

但是当我在以下代码中使用 '\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])
Run Code Online (Sandbox Code Playgroud)

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

(column1)   (column2)
  aaa1
  bbb2
Run Code Online (Sandbox Code Playgroud)

小智 13

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

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)
Run Code Online (Sandbox Code Playgroud)