您遇到的問題很可能是由於行尾標記存在問題。
- 視窗/ 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線也是線。 –