简体   繁体   English

python:在文件中写★

[英]python: writing ★ in a file

I am trying to use: 我正在尝试使用:

text = "★"
file.write(text)

In python 3. But I get this error message: 在python 3.但我收到此错误消息:

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

How can I print the symbol ★ in a file in python? 如何在python文件中打印符号★? This is the same symbol that is being used as star ratings. 这与用作星级的符号相同。

By default open uses the platform default encoding (see docs ): 默认情况下, open使用平台默认编码(请参阅docs ):

encoding is the name of the encoding used to decode or encode the file. encoding是用于解码或编码文件的编码的名称。 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. 默认编码取决于平台(无论locale.getpreferredencoding()返回),但可以使用Python支持的任何文本编码。 See the codecs module for the list of supported encodings. 有关支持的编码列表,请参阅codecs模块。

This might not be an encoding that supports not-ascii characters as you noticed yourself. 这可能不是您自己注意到的支持非ascii字符的编码。 If you know that you want utf-8 then it's always a good idea to provide it explicitly: 如果你知道你想要utf-8那么明确地提供它总是一个好主意:

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

Using the with context manager also makes sure there is no file handle around in case you forget to close or it throws an exception before you close the handle. 使用with context manager还可以确保在关闭句柄之前忘记关闭或抛出异常时没有文件句柄。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM