Unicode 写入失败:charmap 无法编码字符

Unicode writing fail: charmap can't encode character

我有一篇文章,其中有一个摘要。我用一些正则表达式抓取了这个摘要,因为文本总是具有相同的结构。
摘要中有一个句子 "NAME is classified as ....",我必须将其替换为文本中抓取的标题,该标题由逗号分隔的 word1 和 word2 组成。只要我这样做,它就可以正常工作(因此我不会添加完整的代码,因为它非常大而且我做不到,而且无论如何问题不在我将提供的范围之外。
我需要根据 word1 添加 unicode 字符 \u2191 或 \u2193,这与字典中的正值或负值相关联。这必须在替换句子之前完成。 我的代码基本上如下:

import re
import io
file=open(Summaries_file,'a')#also tried open(Summaries_file,'a', encoding="UTF_16_LE") and file=io.open(Summaries_file,'a', encoding="UTF_16_LE")
code_dict["page"]="Word1\u2191"
page="page"
summary = "Data is: 111919919. Name is classified as an infered value".
print(summary)
#OUTPUT>"Data is: 111919919. Name is classified as an infered value".
title= "Word1, Word2"

#this is the part added to regular code>>>>  

titlelist=title.split(",")
if titlelist[0]==code_dict[page]:
    titlelist[0]=code_dict[page]+"\u2191"
    title=str(titlelist)
    print(titlelist[0])
    #OUTPUT>"Word1↑"#It displays the arrow well
    print(title) #ok, too.
    #OUTPUT>"Word1↑, Word2"

 #We go back to the end of the normal code
insert=re.compile("is classified as")
print(type(summary))
#<class 'str'>
summary=str(insert.sub(title, summary))
print(summary)
#OUTPUT>"Data is: 111919919. Name Word1↑, Word2 an infered value".

print("passed")
file.write(title+'\n')
file.write(summary+'\n')

然后追溯(最近调用最后):

File "<ipython-input-1-6bc913872cc9>", line 1, in <module>
runfile('C:/Python Scripts/txtad.py', wdir='C:/Users/Laurent/Documents/Python Scripts')

File "C:\Anaconda3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 699, in runfile
execfile(filename, namespace)

File "C:\Anaconda3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 88, in execfile
exec(compile(open(filename, 'rb').read(), filename, 'exec'), namespace)

File "C:/Python Scripts/txtad", line 380, in <module>
file.write(title+'\n')

File "C:\Anaconda3\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 '\u2191' in position 11: character maps to <undefined>

现在,我想不通,我严重卡在这个问题上。
我不知道为什么它首先无法写入,因为它显示了很好的标志,并且我在某些测试中明确编码到正确的系统,甚至使用正确的编码打开文件。

我尝试了各种你可以在那里阅读的内容:

原来的代码确实比较大,但我试了一下,效果一样,而且输入类型完全一致。

我读了这些:

UnicodeEncodeError: 'charmap' codec can't encode characters
Python, Unicode, and the Windows console
python 3.2 UnicodeEncodeError: 'charmap' codec can't encode character '\u2013' in position 9629: character maps to <undefined>
最后,它们比其他任何东西都更令人困惑。

无论如何问题并不像其他控制台那样出在控制台上 post 因为问题出在未显示的写入指令上,此外,字符在我的控制台上显示得很好.. .
我真的不知道发生了什么以及如何处理这个问题。
感谢您的见解。

我终于通过阅读这篇文章和链接的文章解决了这个问题,并且 TadhgMcDonald-Jensen 的评论; Writing Unicode text to a text file?

实际上我只需要打开(文件,"wb",)并在写入每个字符串时进行编码(因为它们不是字节)。 我想我可以使用 io 或编解码器导入并使用向后兼容性打开。