2017-08-29 47 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 –