0

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.

DannyD
  • 2,732
  • 16
  • 51
  • 73
  • And what's wrong with your solution? By the way, excel default separator is not a tab, but semicolon. It is possible to load table separated data, but somewhat tricky. – alko Nov 28 '13 at 18:27
  • 1
    Your code certainly writes the row `hi\thow\tgoes\tit\r\n`, but could be made simpler with `writer.writerow(['hi', 'how', 'goes', 'it'])` What problems are you having, specifically? – Martijn Pieters Nov 28 '13 at 18:31
  • 1
    Note that the *default* dialect is already the Excel CSV dialect. Are you certain you want to use tabs as the delimiter here? You could also use `dialect='excel-tab'` to get the pre-configured tab-delimited Excel dialect. – Martijn Pieters Nov 28 '13 at 18:33
  • 2
    Last but not least, are you using Python 2 or 3? If Python 3, then you need to open the file object slightly differently: `with open('test.csv', 'w', newline='') as csvfile:` – Martijn Pieters Nov 28 '13 at 18:34
  • cool, I changed the delimiter to commas and that worked. thanks – DannyD Nov 28 '13 at 18:37
  • and I'm using Python 2 so my example worked – DannyD Nov 28 '13 at 18:38
  • 2
    @RDoolabh: In that case just omit the whole `delimiter` argument; commas are the default. – Martijn Pieters Nov 28 '13 at 18:39

1 Answers1

0

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.

Community
  • 1
  • 1
Tim Wilder
  • 1,607
  • 1
  • 18
  • 26