如何将 chr(931) 保存到 windows 上的文件中?

How save chr(931) in a file on windows?

x = open("file.txt",'w')
s = chr(931) # 'Σ'
x.write(s)

错误

Traceback (most recent call last):
File "C:\Python34\lib\encodings\cp1252.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u03a3' in position 0: character maps to <undefined>

即使我将字符“Σ”保存在 Windows txt-editor 代码 UTF-8 下,然后在 python 中打开,return 也将是 ' £' 而不是我期望的 Σ.

我不明白为什么 python 解释符号错误,因为它是 utf-8 或者这是 windows 中的问题?

我通过保存为字节而不是字符串来解决问题

def save_byte():
    x = open("file.txt",'wb')
    s = chr(931) # 'Σ'
    s = s.encode()
    x.write(s)
    x.close()

输出: Σ

您的默认编码似乎是 cp1252,而不是 utf-8。 您需要指定编码,以确保它是 utf-8。

这很好用:

with open('outfile.txt', 'w', encoding='utf-8') as f:
    f.write('Σ')

这会引发您的错误:

with open('outfile.txt', 'w', encoding='cp1252') as f:
    f.write('Σ')