2

I want to output a list of dictionaries to a CSV file.

I have the following code :

# -*- coding: utf-8 -*-
import csv

items = [{'ởne': 1, 'twở': 2}, {'ởne': 1, 'twở': 2}]
# Note the usage of the "ở" character, aka "\u1edf"

with open('output.csv', 'w') as f:
    fieldnames = items[0].keys() # fetching the keys of the first item as fieldnames
    w = csv.DictWriter(f, fieldnames=fieldnames, delimiter=';', lineterminator='\n')
    w.writeheader()
    w.writerows(items)

This fails with the following error :

UnicodeEncodeError: 'charmap' codec can't encode character '\u1edf' in position 0: character maps to

How can I get my items to properly output to CSV ?

Brachamul
  • 1,886
  • 2
  • 21
  • 34
  • 1
    specify the correct encoding in `open()`. – AChampion Jun 20 '18 at 13:51
  • Possible duplicate of [Python DictWriter writing UTF-8 encoded CSV files](https://stackoverflow.com/questions/5838605/python-dictwriter-writing-utf-8-encoded-csv-files) – Mayhem Jun 20 '18 at 14:14
  • @Mayhem i've read through that threat, and people are saying that Python 3 should rid us of this issue. I'm using Python 3 and still have it. – Brachamul Jun 20 '18 at 14:21
  • 1
    @AChampion, works like a charm, thank you. I tried adding the `encoding="utf-8"` to the DictWriter args, but that didn't work, I didn't think to put them in `open`. Thanks again ! – Brachamul Jun 20 '18 at 14:26

0 Answers0