我试图制作一个文本文件,其中包含所有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和使整个字符串成一行并附加一个新行到文件结尾。
为什么要以二进制模式打开文本文件?为什么在打开文件时不指定编码?你为什么会认为只有54607个可打印的字符? –
默认写入模式是文本。使用'open('filename','wb')'以二进制模式写入。 –
我看不到你的换行失败。 – usr2564301