2016-04-25 84 views
0

我在波蘭的一個字作爲一個字符串變量,我需要打印到文件:如何使用變音符打印到文件的字符串?

# coding: utf-8 

a = 'ilośc' 
with open('test.txt', 'w') as f: 
    print(a, file=f) 

這將引發

Traceback (most recent call last): 
    File "C:/scratches/scratch_3.py", line 5, in <module> 
    print(a, file=f) 
    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 '\u015b' in position 3: character maps to <undefined> 

尋找已有答案(with .decode("utf-8"),或with .encode("utf-8")),並嘗試各種咒語我終於管理了要創建的文件。

不幸的是寫的是b'ilośc'而不是ilośc。當我在打印到文件之前嘗試對其進行解碼時,我回到了初始錯誤和相同的回溯。

如何將包含變音符的str寫入文件,以便它是字符串而不是字節表示形式?

+0

什麼Python版本您使用的? Python 2.x中的編碼是一種痛苦... – linusg

+0

@linusg你在問題 – user312016

+0

@ user312016中清楚地看到Python34對不起,沒有看到! – linusg

回答

1

回溯說,你試圖保存'ś''\u015b')使用cp1252編碼(默認爲locale.getpreferredencoding(False)人物 - 您的Windows ANSI代碼頁)無法表示該Unicode字符(有超過一百萬個Unicode字符,而cp1252是一個只能表示256個字符的單字節編碼)。

使用的字符編碼,可以代表所需的字符:

with open(filename, 'w', encoding='utf-16') as file: 
    print('ilośc', file=file) 
1
a = 'ilośc' 
with open('test.txt', 'w') as f: 
    f.write(a) 

可以使用二進制模式,即使寫入文件:

a = 'ilośc' 
with open('test.txt', 'wb') as f: 
    f.write(a.encode())