【发布时间】:2015-12-16 18:31:00
【问题描述】:
假设包含一系列整数的文件名为 numbers.txt 并且存在于计算机磁盘上。编写一个程序,读取文件中存储的所有数字并计算它们的总数。
程序没有返回任何错误,但我得到了错误的总数。我得到 5,750,884.00,应该得到 284.00
这是我目前想出的:
def main():
# Accumulator.
total=0.0
try:
# Open the file
infile = open('numbers.txt', 'r')
#read the values from the file and accumulate them.
for line in infile:
amount = float(line)
total+=amount
# Close the file.
infile.close()
except exception as error:
print(err)
else:
# Print the total.
print(format(total,',.2f'))
main()
【问题讨论】:
-
啊,我错过了你给出预期输出的那一行。你给文件提供什么输入?
-
您的代码在我看来是正确的;你怎么知道预期的输出是什么?
-
我复制并粘贴了这段代码,创建了自己的 numbers.txt,它运行良好。
-
我在这里看到的唯一错误不会影响你得到的总和;无用的
except块对其捕获的异常使用两个不同的名称,并且文件以异常不安全的方式关闭。 -
您是否得到相同的答案:
sum(map(int, open('numbers.txt')))?或者,如果一行上可能有多个整数并忽略其他任何内容;你可以use this。虽然如果行不是很长并且它们只包含以空格分隔的整数,那么sum(i for line in open('numbers.txt') for i in map(int, line.split()))也可以。
标签: python python-3.x