Writing CSV file with umlauts causing “UnicodeEncodeError: 'ascii' codec can't encode character”

后端 未结 2 476
无人共我
无人共我 2021-01-15 18:28

I am trying to write characters with double dots (umlauts) such as ä, ö and Ö. I am able to write it to the file with data.encode(\"utf-8\") but the result

相关标签:
2条回答
  • 2021-01-15 18:38

    This solution should work on both python2 and 3 (not needed in python3):

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    import csv
    data="ääÖ"
    with open("test.csv", "w") as fp:
        a = csv.writer(fp, delimiter=";")
        a.writerows(data)
    

    Credits to: Working with utf-8 encoding in Python source

    0 讨论(0)
  • 2021-01-15 18:54

    Add a parameter encoding to the open() and set it to 'utf8'.

    import csv
    
    data = "ääÖ"
    with open("test.csv", 'w', encoding='utf8') as fp:
        a = csv.writer(fp, delimiter=";")
        a.writerows(data)
    

    Edit: Removed the use of io library as open is same as io.open in Python 3.

    0 讨论(0)
提交回复
热议问题