【发布时间】:2013-06-24 10:46:18
【问题描述】:
似乎 Python 的 UTF-8 编码(codecs 包)将 Unicode 字符 28、29 和 30 解释为行尾。为什么?我怎样才能阻止它这样做?
示例代码:
with open('unicodetest.txt', 'w') as f:
f.write('a'+chr(28)+'b'+chr(29)+'c'+chr(30)+'d'+chr(31)+'e')
with open('unicodetest.txt', 'r') as f:
for i,l in enumerate(f):
print i, l
# prints "0 abcde" with special characters in between.
这里的重点是它像我期望的那样将其读取为一行。现在,当我使用 codecs 以 UTF-8 读取它时,它会将其解释为多行。
import codecs
with codecs.open('unicodetest.txt', 'r', 'UTF-8') as f:
for i,l in enumerate(f):
print i, l
# 0 a
# 1 b
# 2 c
# 3 de
# (again with the special characters after each a, b, c, d
字符 28 到 31 被描述为“信息分隔符四”到“一”(按此顺序)。有两件事让我印象深刻:1)28 到 30 被解释为行尾,2)31 不是。这是预期的行为吗?我在哪里可以找到哪些字符被解释为行尾的定义?有没有办法不将它们解释为行尾?
谢谢。
edit 忘记在codecs.open 中复制“UTF-8”参数。我的问题中的代码现已更正。
【问题讨论】:
-
如果以
'rb'模式打开文件会怎样? -
没什么区别。
-
@Paul,你可以回答你自己的问题,如果你愿意,可以接受它
标签: python unicode encoding utf-8 line-endings