2016-06-11 99 views
-2

我試圖製作一個文本文件,其中包含所有54607個可打印字符,但每行只能包含80個字符以提高可讀性。如何在二進制模式下將換行符寫入文本文件

utf_all = ' !"#$'...' 
lines = '\n'.join(utf_all[i:i+80] for i in range(0, 54607, 80)) 
file = open('allchars.txt', 'w').write(lines) 

即返回錯誤消息

UnicodeEncodeError: 'charmap' codec can't encode characters in position 193-243: character maps to <undefined>

如果我嘗試編碼字符和二進制模式寫入它忽略了換行\ n和使整個字符串成一行並附加一個新行到文件結尾。

+0

爲什麼要以二進制模式打開文本文件?爲什麼在打開文件時不指定編碼?你爲什麼會認爲只有54607個可打印的字符? –

+0

默認寫入模式是文本。使用'open('filename','wb')'以二進制模式寫入。 –

+0

我看不到你的換行失敗。 – usr2564301

回答

-1

你的代碼在python3.5中可以正常工作。然而,你將文件作爲文本文件打開,那不是你想要的嗎?

如果我

open('allchars.txt', 'wb').write(lines) 

替換它,然後我不得不添加encode('utf-8')lines

file = open('allchars.txt', 'wb').write(lines.encode('utf-8')) 

編輯: 我的代碼如下:

utf_all = ''.join([chr(i) for i in range(2**16)]) 
lines = '\n'.join(utf_all[i:i+80] for i in range(0, 54607, 80)) 
file = open('allchars.txt', 'wb').write(lines.encode('utf-8')) 

我的文字編輯器將在80個字符後打開這個包裝(gedit

+0

你從哪裏獲得'utf_all'值? –

+0

看到我更新的anser – DomTomCat