How write 'Ñ' in a file using python

亡梦爱人 提交于 2021-02-19 08:05:10

问题


I know that the encoding can be declared this way:

# -*- coding: utf-8 -*-

But when i try to write 'ñ' in a file, is write 'Ã' instead.

I also try of this way (like is write here in the docs)

import codecs

f = codecs.open('output', encoding='utf-8')
f.write("ñÑ")

but it raise:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)

回答1:


You are using codecs.open(), producing a file object that expects unicode objects. You are, however, passing in a byte string, so Python has to decode to unicode first using the default ASCII codec. This is why you get a decoding error where the ASCII codec failed to decode your UTF-8 bytes.

Decode your string, use a unicode string literal, or use open() instead of codecs.open().

Each of these will work:

# -*- coding: utf-8 -*-
import codecs
with codecs.open('output', encoding='utf-8') as f:
    f.write(u"ñÑ")

or

# -*- coding: utf-8 -*-
import codecs
with codecs.open('output', encoding='utf-8') as f:
    f.write("ñÑ".decode('utf8'))

or

# -*- coding: utf-8 -*-
with open('output') as f:
    f.write("ñÑ")

codecs.open() does take a codec, but that tells the file object how to encode unicode objects to bytes.




回答2:


Try fwrite(u'ñ') The u before the string makes it a different kind of string...



来源:https://stackoverflow.com/questions/32291524/how-write-%c3%91-in-a-file-using-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!