开发者

carriage characters are lost in the resulted string when reading a file on windows

When reading a txt file in windows by python, carriage characoters are lost in resulted string.

c:/text.txt

aaa\r\nbbb\r\nc开发者_高级运维cc\r\nddd

code:

input = open('c:/text.txt')
str = input.read()
import repr
for i,ch in enumerate(str):
    print i,ord(ch),repr.repr(ch)

result:

0 97 'a'
1 97 'a'
2 97 'a'
3 10 '\n'
4 98 'b'
5 98 'b'
6 98 'b'
7 10 '\n'
8 99 'c'
9 99 'c'
10 99 'c'
11 10 '\n'
12 100 'd'
13 100 'd'
14 100 'd'

you can see that all carriage characters are lost. Any suggestion appreciated.

Thanks.


If you open the file in text mode, Windows line endings \r\n are automatically substituted by standard line endings \n. To prevent this from happening, open the file in binary mode:

input = open('c:/text.txt', 'rb')
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜