2016-05-10 36 views
2

我正在寫一個程序,我正在從存儲在文件中的數字進行簡單的計算。但是,它一直返回一個ValueError。有什麼我應該改變的代碼或如何編寫文本文件?如何讀取python文本文件中的數字?

的文件是:

def main(): 

    number = 0 
    total = 0.0 
    highest = 0 
    lowest = 0 

    try: 
     in_file = open("donations.txt", "r") 

     for line in in_file: 
      donation = float(line) 

      if donation > highest: 
       highest = donation 

      if donation < lowest: 
       lowest = donation 

      number += 1 
      total += donation 

      average = total/number 

     in_file.close() 

     print "The highest amount is $%.2f" %highest 
     print "The lowest amount is $%.2f" %lowest 
     print "The total donation is $%.2f" %total 
     print "The average is $%.2f" %average 

    except IOError: 
     print "No such file" 

    except ValueError: 
     print "Non-numeric data found in the file." 

    except: 
     print "An error occurred." 

main() 

和文本文件,它是閱讀過的是

John Brown 
12.54 
Agatha Christie 
25.61 
Rose White 
15.90 
John Thomas 
4.51 
Paul Martin 
20.23 
+0

時,它讀取發生在「約翰·布朗」行麼?看起來你沒有跳過其他所有行,這只是一個名字。它在哪裏定義第一次最高? – flyingmeatball

+0

[如何從Python中的文件讀取數字?]可能的重複(http://stackoverflow.com/questions/6583573/how-to-read-numbers-from-file-in-python) – Li357

回答

1

如果您無法讀取線,跳到下一個。

for line in in_file: 
    try: 
     donation = float(line) 
    except ValueError: 
     continue 

清理代碼有點....

with open("donations.txt", "r") as in_file: 
    highest = lowest = donation = None 
    number = total = 0 
    for line in in_file: 
     try: 
      donation = float(line) 
     except ValueError: 
      continue 
     if highest is None or donation > highest: 
      highest = donation 

     if lowest is None or donation < lowest: 
      lowest = donation 

     number += 1 
     total += donation 

     average = total/number 

print "The highest amount is $%.2f" %highest 
print "The lowest amount is $%.2f" %lowest 
print "The total donation is $%.2f" %total 
print "The average is $%.2f" %average 
相關問題