如何在python的文本文件中读取数字?

时间:2016-05-10 20:34:15

标签: python python-2.7

我正在编写一个程序,我正在根据存储在文件中的数字进行简单的计算。但是,它继续返回ValueError。我应该在代码中更改某些内容或者如何编写文本文件?

文件是:

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

1 个答案:

答案 0 :(得分: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