我想寫一個代碼,我使用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
爲什麼省略我的第一行?
因爲你讀了循環前的第一行。 – BrenBarn
因爲您在閱讀while循環內的行時跳過第一行,因爲您已經讀取了循環外的第一行。 – Li357
感謝您的反饋!我想到了。 – cxNoob