csv export: support for bools and lists
[edumed.git] / edumed / utils.py
1 # -*- coding: utf-8 -*-
2 import codecs
3 import csv
4
5 import cStringIO
6
7
8 # source: https://docs.python.org/2/library/csv.html#examples
9 class UnicodeCSVWriter(object):
10     """
11     A CSV writer which will write rows to CSV file "f",
12     which is encoded in the given encoding.
13     """
14
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)
19         self.stream = f
20         self.encoder = codecs.getincrementalencoder(encoding)()
21
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)
31         # empty queue
32         self.queue.truncate(0)
33
34     def writerows(self, rows):
35         for row in rows:
36             self.writerow(row)