编程语言
首页 > 编程语言> > python:在文件中写★

python:在文件中写★

作者:互联网

我正在尝试使用:

text = "★"
file.write(text)

在python 3.但我收到此错误消息:

UnicodeEncodeError: 'ascii' codec can't encode characters in position 0: ordinal not in range(128)

如何在python文件中打印符号★?这与用作星级的符号相同.

解决方法:

默认情况下,open使用平台默认编码(请参阅docs):

encoding is the name of the encoding used to decode or encode the file. This should only be used in text mode. The default encoding is platform dependent (whatever locale.getpreferredencoding() returns), but any text encoding supported by Python can be used. See the codecs module for the list of supported encodings.

这可能不是您自己注意到的支持非ascii字符的编码.如果你知道你想要utf-8那么明确地提供它总是一个好主意:

with open(filename, encoding='utf-8', mode='w') as file:
    file.write(text)

使用with context manager还可以确保在关闭句柄之前忘记关闭或抛出异常时没有文件句柄.

标签:python,file,python-3-x,non-ascii-characters
来源: https://codeday.me/bug/20190611/1216302.html