2017-08-29 23 views
2

我试图用python写一些希伯来文本到.txt文件,但是看到希伯来语是非ascii和非utf -8我收到错误。我试图在文本文件中获取文本字符,而不是表示它。我的堆栈跟踪的如何写一个unicode字符到utf-8不支持的文件,python

hebrew_word = "שלום" 

file = open("file_with_hebrew.txt", "w") 
file.writelines(hebrew_word) 
file.close() 

部分:

UnicodeEncodeError: 'charmap' codec can't encode character '\u05e9' in position 0: character maps to <undefined> 
+0

“希伯来语非UTF-8”?呃,不行。这是完美的UTF-8。 – deceze

回答

2
hebrew_word = "שלום" 

with open('file_with_hebrew.txt', 'w', encoding='utf-8') as file: 
    #         ^^^^^^^^^^^^^^^^ 
    file.writelines(hebrew_word) 

确保指定打开文件时的编码;在你的情况下,它默认编码不能代表希伯来语。

1

你的脚本工作得很好。你做对了,UTF-8可以打印这些字符。你在什么平台上使用什么Python版本?

open() DOC:

在文本模式下,如果编码未指定使用的编码是 取决于平台:是locale.getpreferredencoding(假)被调用 获取当前本地编码。

所以,你应该指定编码当打开文件到你的平台不具备UTF-8作为默认情况下写:

hebrew_word = "שלום" 

with open("file_with_hebrew.txt", "w", encoding='UTF-8') as file 
    file.writelines(hebrew_word) 
+0

我正在使用python 3.5.1 @deceze答案作品通过在开始处宣布编码 –

+0

正确。看看我在答案中链接的文档,在那里解释得非常好。顺便说一句,你正在运行哪个操作系统脚本? –

+0

我正在使用Windows –