如何使用python在文件中写入'Ñ' [英] How write 'Ñ' in a file using python

查看:60
本文介绍了如何使用python在文件中写入'Ñ'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道可以这样声明编码:

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.

我也尝试过这种方式(比如在文档中写here)

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

import codecs

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

但它提高了:

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

推荐答案

您正在使用 codecs.open(),生成一个需要 unicode 的文件对象对象.但是,您传入的是一个字节字符串,因此 Python 必须首先使用默认的 ASCII 编解码器解码为 unicode.这就是为什么您会收到 解码 错误,其中 ASCII 编解码器无法解码您的 UTF-8 字节.

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.

解码您的字符串,使用 unicode 字符串文字,或使用 open() 而不是 codecs.open().

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

这些都可以工作:

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

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

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

codecs.open() 确实需要一个编解码器,但这会告诉文件对象如何将 unicode 对象编码为字节.

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

这篇关于如何使用python在文件中写入'Ñ'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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