1

I need to print headers and data rows to a CSV file. Here is my code:

import csv

import sys

  with open(r'C:\Users\testuser\Desktop\raw_inpuy.csv','rb') as csvfile:

        reader=csv.reader(csvfile,delimiter=',')
        first=True
        data={}
        for row in reader:
            if first:
                 first= False
                   continue
            if not int(row[1]) in data:
                 data[int(row[1])]=[]
               data[int(row[1])].append(float(row[3]))


    with open (r'C:\Users\testuser\Desktop\outcome.csv','wb') as f_out:
        outwriter=csv.writer(f_out,delimiter=',')
       f_out.write(";".join(['Size','S1','S2','S3','S4']))
       for item in data:
        row=[item]
        row.extend(data[item])
        f_out.write(";".join(map(str,row)))

I get this error:

**ERROR Expected a character buffer obj**
2
  • You need to use csv.writer to create a writer object Commented Aug 17, 2015 at 21:50
  • No! you can't just rewrite the question completely based on first answers. rollback, accept an answer and ask another question! Commented Aug 17, 2015 at 22:11

2 Answers 2

3

You should feed writer.write with an str not a list:

 writer.write(";".join(['Size','S1','S2','S3','S4']))

also:

 writer.write(";".join(map(str, row)))
Sign up to request clarification or add additional context in comments.

2 Comments

New error for the last line is: 'sequence item 0: expected string, int found' what I am writing to the csv consists of strings and integers
try: writer.write(";".join(map(str, row)))
0

Instead of trying to build your own CSV records, let the csv module handle it. Like this:

import csv

data = [[10, 'foo', 'bar', 'blue', 'green'],
        [20, 'bar', 'foo', 'blue', 'green'],
        [30, 'ba', 'bar', 'red', 'white']]

with open (r'C:\Users\testuser\Desktop\outcome.csv','w') as file:
  writer = csv.writer(file)
  writer.writerow(['Size','S1','S2','S3','S4'])
  for row in data:
    writer.writerow(row)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.