问题
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