[英]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.
但是,它不断返回 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
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.