我收到以下错误:
Traceback (most recent call last):
File "C:\Books\Python\gsearch.py", line 21, in <module>
text_file.write(titles)
File "C:\Program Files\Python 3.5\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 '\u2190' in position 2936: character maps to <undefined>
线路text_file.write(titles)
应该写入一些存储在 titles
中的文本变量到文件。我读过其他问题,例如 this one在 Stackoverflow 上。但是,它们专门使用 print
处理控制台输出。 。我想将文本写入文件。
最佳答案
您必须在打开时为文件对象指定正确的编码。这可以通过将编码传递给 open()
函数的 encoding
关键字参数来完成。
例如:
with open(file_name, 'w', encoding='utf8') as text_file:
pass
关于 python : UnicodeEncodeError: 'charmap' codec can't encode character '\u2190' in position 2936,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41421935/