【问题标题】:How to read numbers in a text file for python?如何读取python文本文件中的数字?
【发布时间】:2016-09-06 00:26:35
【问题描述】:

我正在编写一个程序,我正在对存储在文件中的数字进行简单的计算。但是,它继续返回 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

【问题讨论】:

  • 当它读入“John Brown”行时会发生什么?似乎您没有跳过所有其他行,这只是一个名称。但它第一次定义的最高值在哪里?

标签: python python-2.7


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-10
    • 1970-01-01
    相关资源
    最近更新 更多