python中csv.writer的选项卡''t'的定界符 [英] delimiter of tab '\t' of csv.writer in python

查看:158
本文介绍了python中csv.writer的选项卡''t'的定界符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想以以下形式将字典写到csv中:

I want to write the dict into csv as this form:

(column1)   (column2)
  aaa           1     
  bbb           2

但是当我使用'\t'作为定界符时以下代码:

but when I use the '\t' as the delimiter in the following code:

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就像

I could not get the desired ouput, instead the created csv will be like

(column1)   (column2)
  aaa1
  bbb2


推荐答案

您正在将输出转换为结合了键和值的列表。

You are converting the output into a list which is combining the key and value. Use the following instead.

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)

这篇关于python中csv.writer的选项卡''t'的定界符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆