Carl
Carl

Reputation: 55

How to read numbers in a text file for python?

I'm writing a program where I'm doing simple calculations from numbers stored in a file. However, it keeps on returning a ValueError. Is there something I should change in the code or how the text file is written?

The file is:

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()

and the text file it is reading of off is

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

Upvotes: 2

Views: 1418

Answers (1)

Alexander
Alexander

Reputation: 109510

If you can't read a line, skip to the next one.

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

Cleaning up your code a bit....

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

Upvotes: 1

Related Questions