Python 3: CSV utf-8 encoding

Viewed 7141

I'm trying to write a CSV with non-ascii character using Python 3.

import csv

with open('sample.csv', 'w', newline='', encoding='utf-8') as csvfile:
    spamwriter = csv.writer(csvfile, delimiter=' ',
                            quotechar='|', quoting=csv.QUOTE_MINIMAL)
    spamwriter.writerow("嗨")

When I open the Excel file, see å—¨ instead. Am I doing something wrong here?

1 Answers

You need to indicate to Excel that this is a UTF-8 file; it won't assume so automatically.

You do this by putting a Byte Order Mark (BOM) at the start of the file:

with open('sample.csv', 'w', newline='', encoding='utf-8') as csvfile:
    csvfile.write('\ufeff')
Related