使用Python打印到CSV文件

时间:2015-08-17 21:48:04

标签: python csv

我需要将标题和数据行打印到CSV文件。这是我的代码:

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

我收到此错误:

**ERROR Expected a character buffer obj**

2 个答案:

答案 0 :(得分:3)

您应该使用writer.write而非str提供list

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

也:

 writer.write(";".join(map(str, row)))

答案 1 :(得分:0)

csv模块处理它,而不是尝试构建自己的CSV记录。像这样:

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)