37,719
社区成员
发帖
与我相关
我的任务
分享
class StockPipelineCSV(object):
def open_spider(self,spider):
self.file = open('stocks_01.csv', 'w')
self.exporter = CsvItemExporter(self.file)
self.exporter.start_exporting()
def close_spider(self,spider):
self.exporter.finish_exporting()
self.file.close()
def process_item(self, item, spider):
self.exporter.export_item(item)
return item
#exporters.py
def export_item(self, item):
if self._headers_not_written:
self._headers_not_written = False
self._write_headers_and_set_fields_to_export(item)
fields = self._get_serialized_fields(item, default_value='',
include_empty=True)
values = list(self._build_row(x for _, x in fields))
self.csv_writer.writerow(values)
def _build_row(self, values):
for s in values:
try:
yield to_native_str(s, self.encoding)
except TypeError:
yield s
#python.py
def to_native_str(text, encoding=None, errors='strict'):
""" Return str representation of `text`
(bytes in Python 2.x and unicode in Python 3.x). """
if six.PY2:
return to_bytes(text, encoding, errors)
else:
return to_unicode(text, encoding, errors)
# coding: utf-8
import csv
csvfile = open('D://t.csv', 'w+b')
writer = csv.writer(csvfile)
writer.writerow([str.encode('列1'), str.encode('列2'), str.encode('列3')])
data = [
str.encode('值1'), str.encode('值2'), str.encode('值3')
]
writer.writerow(data)
csvfile.close()
#python.py
def to_native_str(text, encoding=None, errors='strict'):
""" Return str representation of `text`
(bytes in Python 2.x and unicode in Python 3.x). """
if six.PY2:
return to_bytes(text, encoding, errors)
else:
return to_unicode(text, encoding, errors)