1 # -*- coding: utf-8 -*-
8 # source: https://docs.python.org/2/library/csv.html#examples
9 class UnicodeCSVWriter(object):
11 A CSV writer which will write rows to CSV file "f",
12 which is encoded in the given encoding.
15 def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
16 # Redirect output to a queue
17 self.queue = cStringIO.StringIO()
18 self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
20 self.encoder = codecs.getincrementalencoder(encoding)()
22 def writerow(self, row):
23 self.writer.writerow([s.encode("utf-8") for s in row])
24 # Fetch UTF-8 output from the queue ...
25 data = self.queue.getvalue()
26 data = data.decode("utf-8")
27 # ... and reencode it into the target encoding
28 data = self.encoder.encode(data)
29 # write to the target stream
30 self.stream.write(data)
32 self.queue.truncate(0)
34 def writerows(self, rows):