如何读取python文本文件中的数字?
我在写一个程序,在这个程序中,我根据存储在文件中的数字进行简单的计算。但是,它会不断返回ValueError。代码中是否有我应该更改的内容或文本文件的编写方式 该文件是:如何读取python文本文件中的数字?,python,python-2.7,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:
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()
如果你看不懂一行,跳到下一行
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
打开(“investments.txt”、“r”),如_文件中所示:
最高=最低=捐赠=无
数字=总数=0
对于\u文件中的行:
尝试:
捐赠=浮动(行)
除值错误外:
持续
如果“最高”为“无”或“捐赠>最高”:
最高=捐款
如果最低值为无或<最低值:
最低=捐赠
数字+=1
总数+=捐款
平均数=总数/数量
打印“最高金额为%.2f”%highest
打印“最低金额为%.2f”%lowest
打印“捐赠总额为%.2f$”%total
打印“平均值为$%.2f”%average
当它读取“John Brown”行时会发生什么?似乎你没有跳过每一行,这只是一个名字。但它第一次定义的最高时间在哪里?可能重复
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