使用变音符编写CSV文件导致“UnicodeEncodeError:”ascii'编解码器不能编码字符“ [英] Writing CSV file with umlauts causing "UnicodeEncodeError: 'ascii' codec can't encode character"

查看:159
本文介绍了使用变音符编写CSV文件导致“UnicodeEncodeError:”ascii'编解码器不能编码字符“的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用双点(umlauts),如ä,ö和Ö写字符。我可以使用 data.encode(utf-8)将其写入文件,但结果 b'\xc3\xa4 \xc3\xa4\xc3\x96'不好(UTF-8作为文字字符)。我想要将ääÖ写入存储到文件中。



如何在Python 3中将数字与变音符字符一起写入CSV文件?





$ ba code





with open(test.csv,w)as fp:
a = csv。作者(fp,delimiter =;)
data = resultFile
a.writerows(data)

追溯:

 文件< ipython-input-280-73b1f615929e> ;,第5行,< module> 
a.writerows(data)
UnicodeEncodeError:'ascii'编解码器不能在15位编码字符\xe4:序号不在范围(128)


解决方案

将参数 encoding code> open()并将其设置为'utf8'

  import csv 

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

编辑:删除使用 io 库作为打开 io.open 在Python 3中。


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 b'\xc3\xa4\xc3\xa4\xc3\x96' is not nice (UTF-8 as literal characters). I want to get "ääÖ" as written stored to a file.

How can I write data with umlaut characters to a CSV file in Python 3?

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

Traceback:

File "<ipython-input-280-73b1f615929e>", line 5, in <module>
  a.writerows(data)
UnicodeEncodeError: 'ascii' codec can't encode character '\xe4' in position 15: ordinal not in range(128)

解决方案

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.

这篇关于使用变音符编写CSV文件导致“UnicodeEncodeError:”ascii'编解码器不能编码字符“的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆