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

A program to read a file and print out the sum of the numbers in the file. The file contains a single floating point numbers separated by commas

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

-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 + 浮动(i) ValueError:无法将字符串转换为浮点数:'.'"

任何帮助将不胜感激!

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)
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

您可以按照以下方式进行:

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))

我们简单地循环遍历文件的每一行,用 , 拆分行上的所有值,并将每一行上的每个值添加到我们的总和中。最后,我们打印出值。

您可以将 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} 格式保留一位小数。

您可以使用生成器打印所有值的总和

with open(filename,"r")as f:
    print sum(float(e) for line in f for e in line.split(","))

>> 125.7