2016-06-11 100 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