编写一个打印出文件中数字总和的程序

时间:2015-03-20 02:31:01

标签: python text

我编写了以下程序,从文件中读取数字。我可以假设每行只包含一个浮点数。

filename = input("Please enter your file name: ")
sum_number = 0

openthefile = open(filename, "r")
for i in openthefile:
    sum_number = sum_number + float(i)
    print("The sum of your numbers is", sum_number)

我给了它一个名为number.txt的文件,其中包含:

8.0
-2.5
100.0
6.5

我的程序打印出来了:

The sum of your numbers is 8.0
The sum of your numbers is 5.5
The sum of your numbers is 105.5
The sum of your numbers is 112.0

但是,我只需要打印出最后一行。

2 个答案:

答案 0 :(得分:2)

sum_number是一个int,当您执行[i]时,您创建的单个元素列表包含i,因此可能会出现错误。

只需改变:

sum_number = sum_number + [i]

sum_number = sum_number + float(i)

你应该没事。注意,您不仅需要将i包装在列表中,而且还需要将其转换为浮点数,否则您将得到类似但不同的错误:

TypeError: unsupported operand type(s) for +: 'int' and 'str'
每条评论

编辑,整个代码为:

filename = input("Please enter your file name: ")
sum_number = 0

openthefile = open(filename, "r")
for i in openthefile:
    sum_number = sum_number + float(i)

print("The sum of your numbers is", sum_number)

答案 1 :(得分:2)

使用with关键字,它使文件处理安全。将每个数字类型转换为float,如下所示:

sum = 0
with open("foo.txt", 'r') as fin:
    for line in fin:
        sum+=float(line)
print sum

foo.txt的内容

2.37
4.35
6.27

输出:

  

12.99

编辑:

不使用with关键字的相同代码:

f = open("foo.txt", 'r')
lines = f.read().splitlines()
f.close()

sum = 0
for l in lines:
    sum+=float(l)

print sum