2013-06-21 71 views
4

我有一個名爲test的文件,該文件具有內容:從Python中的文本文件閱讀 - 第一行被錯過

a 
b 
c 
d 
e 
f 
g 

我使用下面的Python代碼逐行讀取該文件中的行,並打印出:

with open('test.txt') as x: 
    for line in x: 
     print(x.read()) 

這樣做的結果是打印出來,除了第一行的文本文件的內容,即其結果是:

b 
c 
d 
e 
f 
g 

有沒有人有任何想法爲什麼它可能會丟失文件的第一行?

回答

8

因爲for line in x遍歷每一行。

with open('test.txt') as x: 
    for line in x: 
     # By this point, line is set to the first line 
     # the file cursor has advanced just past the first line 
     print(x.read()) 
     # the above prints everything after the first line 
     # file cursor reaches EOF, no more lines to iterate in for loop 

也許你的意思是:

with open('test.txt') as x: 
    print(x.read()) 

打印,一次就全部或者:

with open('test.txt') as x: 
    for line in x: 
     print line.rstrip() 

到逐行打印。後者是推薦的,因爲您不需要一次將文件的全部內容加載到內存中。

+0

這正是我所期待的。非常感謝:D – Riddle

+0

@Riddle沒問題 – jamylak