equal
deleted
inserted
replaced
1 # -*- coding: utf-8 -*- |
|
2 ''' |
|
3 Created on Feb 2, 2012 |
|
4 |
|
5 @author: ymh |
|
6 ''' |
|
7 |
|
8 import cStringIO |
|
9 import csv |
|
10 import codecs |
|
11 |
|
12 class UnicodeWriter: |
|
13 """ |
|
14 A CSV writer which will write rows to CSV file "f", |
|
15 which is encoded in the given encoding. |
|
16 """ |
|
17 |
|
18 def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds): |
|
19 # Redirect output to a queue |
|
20 self.queue = cStringIO.StringIO() |
|
21 self.writer = csv.writer(self.queue, dialect=dialect, **kwds) |
|
22 self.stream = f |
|
23 self.encoder = codecs.getincrementalencoder(encoding)() |
|
24 |
|
25 def writerow(self, row): |
|
26 self.writer.writerow([unicode(s).encode("utf-8") for s in row]) |
|
27 # Fetch UTF-8 output from the queue ... |
|
28 data = self.queue.getvalue() |
|
29 data = data.decode("utf-8") |
|
30 # ... and reencode it into the target encoding |
|
31 data = self.encoder.encode(data) |
|
32 # write to the target stream |
|
33 self.stream.write(data) |
|
34 # empty queue |
|
35 self.queue.truncate(0) |
|
36 |
|
37 def writerows(self, rows): |
|
38 for row in rows: |
|
39 self.writerow(row) |
|