Skip to main content
 首页 » 编程设计

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

2025年04月02日13grandyang

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

请您参考如下方法:

如果你无法阅读一行,请跳到下一行。

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