一个程序,用于读取文件并打印出文件中数字的总和。该文件包含以逗号分隔的单个浮点数

时间:2015-03-20 21:29:07

标签: python file text

例如,如果您的文件包含:

-2.5, 2.0
8.0
100.0, 3.0, 5.1, 3.6
6.5

然后程序的示例运行如下:

Please enter your file name:  nums.txt
The sum of your numbers is 125.7.

我已经运行了该程序,但它给了我一个错误,这样说 " sum_number = sum_number + float(i) ValueError:无法将字符串转换为float:'。'"

任何帮助将不胜感激!

filename = input("Please enter your file name: ")
sum_number = 0
openthefile = open(filename, "r")

for i in openthefile:
    Split = i.split(',')
    Join = "".join(Split)
    print(Join)

for i in Join:
    sum_number = sum_number + float(i)

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

4 个答案:

答案 0 :(得分:1)

您可以将map和sum与生成器表达式一起使用:

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

with open(filename) as f: # closes your file automatically
    print("The sum of your numbers is {:.1f}".format(sum(sum(map(float, line.split(","))) for line in f)))

The sum of your numbers is 125.7

您正在尝试加入所有花车,然后施放,即:

float("100.03.05.13.6")

因此,对于for i in Join:,您将迭代连接字符串的每个字符,这会给出您看到的错误.无法转换为浮点数。

{:.1f}格式为1位小数。

答案 1 :(得分:0)

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

lst = []
with open(filename, 'r') as f:
    for line in f:
        lst.extend(line.split(','))

lst = map(float, lst)

print(sum(lst))  # 125.7

这会创建一个空列表,然后对于每一行,将通过逗号分隔该行的元素添加到列表中。最后两步将元素转换为浮点数并打印总和。

或者,不是跟踪列表中的所有元素,而是跟踪总和:

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

total = 0
with open(filename, 'r') as f:
    for line in f:
        for elem in line.split(','):
            total += float(elem)

print(total)  # 125.7

答案 2 :(得分:0)

您可以使用生成器

打印所有值的总和
with open(filename,"r")as f:
    print sum(float(e) for line in f for e in line.split(","))

>> 125.7

答案 3 :(得分:-1)

您可以按照以下方式执行此操作:

filename = input("Please enter your file name: ")
sum_number = 0
openthefile = open(filename, "r")

for line in openthefile:
    for num in line.split(','):
        sum_number = sum_number + float(num.strip())

print("The sum of your numbers is %.1f" %(sum_number))

我们只是循环浏览文件的每一行,将,上的所有值拆分,然后将每行的每个值添加到总和中。最后,我们打印出值。