1

My code below:

with open('C:\\Users\\...\\Documents\\RP_test_8.txt', 'w') as f:
    cf = csv.DictWriter(f, column_headers, extrasaction='ignore') 
    cf.writeheader()
    cf.writerows(r.data for r in records)

gives me a unicode encode exception:

UnicodeEncodeError                        Traceback (most recent call last)
<ipython-input-141-410d45c40cce> in <module>()
      2     cf = csv.DictWriter(f, column_headers, extrasaction='ignore')
      3     cf.writeheader()
----> 4     cf.writerows(r.data for r in records)

C:\Users\...\AppData\Local\Continuum\anaconda2\lib\csv.pyc in writerows(self, rowdicts)
    156         for rowdict in rowdicts:
    157             rows.append(self._dict_to_list(rowdict))
--> 158         return self.writer.writerows(rows)
    159 
    160 # Guard Sniffer's type checking against builds that exclude complex()

UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 30: ordinal not in range(128)

What is the best way to handle this?

Marlon Abeykoon
  • 9,221
  • 4
  • 41
  • 68
Y. Eman
  • 23
  • 9

1 Answers1

0

You can encode each value in the dictionary as follows and then send the final list of dictionaries to the writerows function. You can also encode the key if needed.

import csv
cf = csv.DictWriter(f, column_headers, extrasaction='ignore')
cf.writeheader()
final_dict_list = []
for r in records:
    for d in r.data:
        final_dict_list.append({k:v.encode('utf8') for k,v in d.items()})
cf.writerows(final_dict_list)
Marlon Abeykoon
  • 9,221
  • 4
  • 41
  • 68
  • Thank you for the detailed answer; but I get an AttributeError:'unicode' object has no attribute 'items' on the line that starts with final_dict_list.append(). Later, I found a workaround; that is adding import unicodecsv. – Y. Eman Jul 19 '18 at 01:16