简体   繁体   中英

Having trouble writing data to csv file in python

I want to output some of my data to a csv file so I can open it in excel. However, I can't even get my simple example to work. This is what I have:

import csv

with open('test.csv','wb') as csvfile:
    writer = csv.writer(csvfile, delimiter='\t')
    writer.writerow(['hi'] + ['how'] + ['goes'] + ['it'])

I want my words to be separated with tabs so that when I open the file in excel, each word becomes a new column.

Are you on Python 3 and getting TypeError: 'str' does not support the buffer interface ?

This thread answers that problem. Python3: writing csv files

Commas work for my excel if you're on 2 and that isn't the problem:

import csv

with open('test.csv', 'wb') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow(['hi', 'how', 'goes', 'it'])

Hmmm Martijn posted the same thing but earlier. Upvote him, don't accept this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM