python csv文件写入失败_新手求助大神~关于csv模块-将数据写入csv文件总是报错,求解!...

该楼层疑似违规已被系统折叠 隐藏此楼查看此楼

代码已简化如下:

import csv

file_order=[*date*,*product_name*,*product_price*,*evaluation_num*]

fields={*date*:*Date*, *product_name*:*Name*, *product_price*:*Price*, *evaluation_num*:*Evaluation*}

file_name=*jd_freezer.csv*

csv_writer=csv.DictWriter(open(file_name,*wb*),fieldnames=file_order,extrasaction=*ignore*,dialect="excel")

csv_writer.writeheader()

file_name.close()

我用的是最新版的python3.4, 关于csv中模块DictWriter的定义如下:

class DictWriter:

def __init__(self, f, fieldnames, restval="", extrasaction="raise",

dialect="excel", *args, **kwds):

self.fieldnames = fieldnames # list of keys for the dict

self.restval = restval # for writing short dicts

if extrasaction.lower() not in ("raise", "ignore"):

raise ValueError("extrasaction (%s) must be *raise* or *ignore*"

% extrasaction)

self.extrasaction = extrasaction

self.writer = writer(f, dialect, *args, **kwds)

def writeheader(self):

header = dict(zip(self.fieldnames, self.fieldnames))

self.writerow(header)

def _dict_to_list(self, rowdict):

if self.extrasaction == "raise":

wrong_fields = [k for k in rowdict if k not in self.fieldnames]

if wrong_fields:

raise ValueError("dict contains fields not in fieldnames: "

+ ", ".join([repr(x) for x in wrong_fields]))

return [rowdict.get(key, self.restval) for key in self.fieldnames]

def writerow(self, rowdict):

return self.writer.writerow(self._dict_to_list(rowdict))

def writerows(self, rowdicts):

rows = []

for rowdict in rowdicts:

rows.append(self._dict_to_list(rowdict))

return self.writer.writerows(rows)

我自己感觉应该没什么问题,可运行总是报错,如下:

Traceback (most recent call last):

File "D:/Python34/jd2.py", line 9, in

csv_writer.writeheader()

File "D:\Python34\lib\csv.py", line 142, in writeheader

self.writerow(header)

File "D:\Python34\lib\csv.py", line 153, in writerow

return self.writer.writerow(self._dict_to_list(rowdict))

TypeError: *str* does not support the buffer interface

意思貌似是说writerow传的参数-字典类型的有问题?可到底是什么原因呢,csv模块中给的就是字典类型的呀,我快崩溃了,本人是初学者菜鸟一只,求各路大侠指点,跪谢

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值