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

后端 未结 2 494
无人共我
无人共我 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

提交回复
热议问题