2016-05-10 1 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 
Смежные вопросы