当前位置:   article > 正文

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

write_csv(rfields_path, rfields)报错

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

代码已简化如下:

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模块中给的就是字典类型的呀,我快崩溃了,本人是初学者菜鸟一只,求各路大侠指点,跪谢

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/175849
推荐阅读
相关标签
  

闽ICP备14008679号