您遇到的问题很可能是由于行尾标记存在问题。
- 视窗/ DOS通常使用
CRLF
(或,\r\n
,或0d0a
以字节为单位)。
- Unix的通常使用
LF
(或\n
,或以字节0a
)
- MacOS的通常使用
CR
(或\r
,或以字节0d
)
下面是一些例子与ASCII编码的文件:
$ hexdump -C test_dos.txt
00000000 68 65 6c 6c 6f 0d 0a 77 6f 72 6c 64 0d 0a |hello..world..|
0000000e
$ hexdump -C test_nix.txt
00000000 68 65 6c 6c 6f 0a 77 6f 72 6c 64 0a |hello.world.|
0000000c
$ hexdump -C test_mac.txt
00000000 68 65 6c 6c 6f 0d 77 6f 72 6c 64 0d |hello.world.|
0000000c
广告你可以看到,单词hello
(68 65 6c 6c 6f
)后面跟着不同的字节分别为,0a
或0d
。在MS记事本中编辑文件时,最有可能会插入CRLF
。由于LF
在软件开发中是最常见的,Notepad ++很可能会添加这些。
现在,你的代码:鉴于以上三个文件,一个类似的代码你得到以下结果:
代码:
files = ('test_dos.txt', 'test_nix.txt', 'test_mac.txt')
for fname in files:
print("Reading {}".format(fname))
with open(fname) as fptr:
for line in fptr:
print("--> {!r}".format(line))
print(80*"-")
输出:
Reading test_dos.txt
--> 'hello\r\n'
--> 'world\r\n'
--------------------------------------------------------------------------------
Reading test_nix.txt
--> 'hello\n'
--> 'world\n'
--------------------------------------------------------------------------------
Reading test_mac.txt
--> 'hello\rworld\r'
--------------------------------------------------------------------------------
正如你可以清楚地看到,Python分裂在\n
字符上,但不会将其从输出中删除。这就是为什么“mac”示例只有一行。
如果您不得不处理来自异质数据源的文件,请考虑启用U
标志为open的“通用换行符”。
下面是一个例子。需要注意的是其唯一改变的事情是U
参数open
:
files = ('test_dos.txt', 'test_nix.txt', 'test_mac.txt')
for fname in files:
print("Reading {}".format(fname))
with open(fname, 'U') as fptr:
for line in fptr:
print("--> {!r}".format(line))
print(80*"-")
输出:
Reading test_dos.txt
--> 'hello\n'
--> 'world\n'
--------------------------------------------------------------------------------
Reading test_nix.txt
--> 'hello\n'
--> 'world\n'
--------------------------------------------------------------------------------
Reading test_mac.txt
--> 'hello\n'
--> 'world\n'
--------------------------------------------------------------------------------
正如你所看到的,并不是所有的文件的行为相同。这可能会提示您在正在阅读文本文件的任何地方胡椒粉U
。不过,我确信有一个很好的理由,它不是默认的! :)
恩,对我来说很好。 –
请注意,“at + gpsinit = 2”和“OK”之间没有行跳,所以我不明白为什么会有17个“空白”行。 – katze
emty线也是线。 –