python: 在文件中写入★

python: writing ★ in a file

我正在尝试使用:

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.

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

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

使用 with 上下文管理器还可以确保周围没有文件句柄,以防您忘记关闭或在关闭句柄之前抛出异常。