2016-10-31 71 views
-3

我想寫一個代碼,我使用while循環來讀取txt文件中的每一行,直到沒有任何內容的行被看到,即\ n。我的txt文件和代碼如下所示:python 3.5爲什麼我的while循環省略了第一行?

I like cats 
But dogs are 
the best 

although a tiger 
would make for 
an awesome pet 



file1 = input("Enter name of file: ") 
openfile1 = open(file1, "r") 
data1 = openfile1.readline().strip() 
while data1 !="": 
    data1 = openfile1.readline().strip() 
    print (data1) 

我希望它打印出來的是:

I like cats 
But dogs are 
the best 

,而是它忽略了第一線,給我:

But dogs are 
the best 

爲什麼省略我的第一行?

+1

因爲你讀了循環前的第一行。 – BrenBarn

+0

因爲您在閱讀while循環內的行時跳過第一行,因爲您已經讀取了循環外的第一行。 – Li357

+0

感謝您的反饋!我想到了。 – cxNoob

回答

0

正如其他人說你已經讀了線一旦所以沒有出現print語句while循環

4

裏面的readline前移至。

此外,還有一種更簡單的打印文件行的方法。

import os 

with open('input.txt') as fl: 
    for line in fl: 
     print(line.strip()) 
+1

使用with語句並遍歷行是Pythonic執行此操作的方式,以便獲得我的投票。 – JasTonAChair

相關問題