该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
代码已简化如下:
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模块中给的就是字典类型的呀,我快崩溃了,本人是初学者菜鸟一只,求各路大侠指点,跪谢