2011-07-08 22 views
6

我有一個.txt文件,我用多行創建。Python 3.2 - readline()跳過源文件中的行

當我使用計數累加器運行for循環時,它跳過了行。

它跳過了頂線,並與第二開始,打印第四,第六,等...

什麼是我失蹤了嗎?

** for your reading pleasure** 
def main(): 
    # Open file line_numbers.txt 
    data_file = open('line_numbers.txt', 'r') 

    # initialize accumulatior 
    count = 1 


    # Read all lines in data_file 
    for line in data_file: 
     # Get the data from the file 
     line = data_file.readline() 

     # Display data retrieved 
     print(count, ": ", line) 

     # add to count sequence 
     count += 1 
+0

我覺得@Shelhammer釘它。我想這是不明顯的,「在」做了一個閱讀。那麼,它的確如此。 – Malvolio

回答

6

嘗試一起刪除「line = data_file.readline()」?我懷疑「for data_file中的行:」也是一個readline操作。

+0

現在它沒有跳過,但它在輸出上計數空白行?所以而不是1-5,其返回1 - 11 –

+0

再一次,完美!謝謝!!! –

6

你for循環迭代data_file,你的readline()與它競爭。擦除line = data_file.readline()行代碼的這個結果:

# Read all lines in data_file 
count = 1 
for line in data_file: 
    # Display data retrieved 
    print(count, ": ", line) 

    # add to count sequence 
    count += 1 
+0

完美!謝謝! –

3

for line in data_file已經得到各行對你的文本 - 在後續調用的ReadLine然後得到以下線。換句話說,刪除對readline的調用將做你想要的。與此同時,你並不需要保持一個累加器變量自己的軌道 - Python有這樣使用enumerate的內置的方式 - 換句話說:

data_file = open('line_numbers.txt', 'r') 
for count, line in enumerate(data_file): 
    ... 
+0

'enumerate()' – bernie

+0

對於OP的薰染,讓我們通過使用'with open('line_numbers.txt')作爲data_file:' –

+0

+1確實爲enumerate()增加了更多的改進。不要忘記它從零開始的數字,所以當爲人類消費打印時,你通常希望在計數上加一個數字。大多數人更喜歡基於1的編號。 – holdenweb