Skip to content
This repository has been archived by the owner on Jan 18, 2020. It is now read-only.

Support Unicode input in the CSV exporter #218

Merged
merged 1 commit into from
Jul 18, 2014
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 22 additions & 1 deletion avocado/export/_csv.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,27 @@
from _base import BaseExporter


class UnicodeWriter(object):
"""
A CSV writer which will write rows to CSV file "f",
which is encoded in the given encoding.
Adapted from https://github.com/jdunck/python-unicodecsv/blob/master/unicodecsv/__init__.py # noqa
"""

def __init__(self, f, dialect=csv.excel, encoding='utf-8', *args, **kwds):
self.encoding = encoding
self.writer = csv.writer(f, dialect, *args, **kwds)

def writerow(self, row):
self.writer.writerow(
[s.encode("utf-8") if 'encode' in dir(s) else s for s in row])

def writerows(self, rows):
for row in rows:
self.writerow(row)


class CSVExporter(BaseExporter):
short_name = 'CSV'
long_name = 'Comma-Separated Values (CSV)'
Expand All @@ -14,7 +35,7 @@ class CSVExporter(BaseExporter):
def write(self, iterable, buff=None, *args, **kwargs):
header = []
buff = self.get_file_obj(buff)
writer = csv.writer(buff, quoting=csv.QUOTE_MINIMAL)
writer = UnicodeWriter(buff, quoting=csv.QUOTE_MINIMAL)

for i, row_gen in enumerate(self.read(iterable, *args, **kwargs)):
row = []
Expand Down