2016-11-12 36 views
1

的向下箭頭()是CP437編碼有效字符。我正在寫一個程序,它需要與此編碼讀取和寫入文件,但是當我嘗試寫包含此字符文件的字符串,我收到以下錯誤:的Python失敗上有效CP437字符

File "C:\Python34\lib\encodings\cp437.py", line 19, in encode 
    return codecs.charmap_encode(input,self.errors,encoding_map)[0] 
UnicodeEncodeError: 'charmap' codec can't encode character '\u2193' in position 0: character maps to <undefined> 

同樣的事情發生了其他CP437字符,例如。 我的代碼如下,如果我做了一些愚蠢的有...

ENCODING = 'CP437' 

def writeFile(name, text): 
    f = open(name, 'w', encoding = ENCODING) 
    f.write(text) 
    f.close() 

根據維基百科,它在指定的編碼無效,所以爲什麼蟒蛇告訴我,否則?我怎樣才能解決這個問題?

+0

「維基百科說,這是有效的」 - 什麼是有效的呢? Python是否積極支持CP437? – usr2564301

+1

@RadLexus我的意思是它顯然在CP437中有效。而且,python在庫中有一個'cp437.py',所以它應該被支持。 – FlipTack

+0

你使用的是什麼版本?蟒蛇3.5.1有很多的unicode棄用的 – rassar

回答

1

你已經鏈接到Wiki頁面說(只是顯示向下箭頭0x19上表):

Although the ROM provides a graphic for all 256 different possible 8-bit codes, some APIs will not print some code points, in particular the range 1-31 and the code at 127. Instead they will interpret them as control characters. For instance many methods of outputting text on the original IBM PC would interpret the codes for BEL, BS, CR and LF. Many printers were also unable to print these characters.

你要編碼的字符,向下箭頭,是與ASCII控制字符EM(End of Medium)相同的字符。舊計劃中的含義取決於上下文。在Python中,上面引用(1-31和127)中提到的字符總是被解釋爲控制字符,而不是可打印字符。

+0

+1,但是你錯過了打印Python解釋爲控制字符的字符的代碼,以及哪些遺留系統將解釋爲向下箭頭。 – Kevin

0

一個謎我但這並做你需要什麼?

f = open('somethin.txt', 'wb') 
s1 = (chr(8595)+chr(8593)+chr(8592)+chr(8594)) . encode ('utf-8') 
s2 = '↓↑←→' . encode ('utf-8') 
f.write(s1) 
f.write(s2) 
f.close() 

S1S2是相同的字節串。

+0

不是真的,因爲我需要用CP437編碼來編寫文件,不過謝謝你的回覆。 – FlipTack

相關問題