Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

delimiter of tab '\t' of csv.writer in python

Tags:

python

csv

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

(column1)   (column2)
  aaa           1     
  bbb           2

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])

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

(column1)   (column2)
  aaa1
  bbb2
like image 976
Nan Avatar asked Mar 08 '17 11:03

Nan


1 Answers

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)
like image 127
user8327054 Avatar answered Sep 30 '22 05:09

user8327054