Search code examples
pythonpython-3.xcsvunicode

Unicode error when writing russian symbols to csv


I want to write cyrillic symbols to csv file but I get unicode encode error. English symbols works perfect. I'm using Python 3.6.2.

UnicodeEncodeError: 'ascii' codec can't encode characters in position 1-6: ordinal not in range(128)

import csv


with open("test.csv", 'w') as csvfile:
    csvfile = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
    hello = 'привет, мир!'
    csvfile.writerow([hello])

Solution

  • Declare the encoding of the file when you open it. newline='' is also required per the csv documentation.

    import csv
    
    with open('test.csv','w',encoding='utf8',newline='') as csvfile:
        csvfile = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
        hello = 'привет, мир!'
        csvfile.writerow([hello])