编写一个程序,读取包含两列数字的文本文件,然后计算每列的总数和平均值?

时间:2014-10-22 15:52:00

标签: python

我必须编写一个程序来读取包含两列数字的文本文件,然后计算每列的总数和平均值。我能够分隔列,但是当我试图找到总和时,我不断收到各种错误,例如“TypeError:+支持的操作数类型+:'int'和'str'”。以下是我到目前为止的情况:

def main():
    print("This program will read the file and calculate the total and average of each column of  numbers")
    filename= input("\nWhat is the name of the file?")
    myfile = open(filename, "r")
    with open("numbers.txt") as myfile:
        for line in myfile:
            parts = line.split()
            if len(parts) > 1:
                total = sum(parts[0])
                total2 = sum(parts[1])
                print(total)
                print(total2)

main()

1 个答案:

答案 0 :(得分:0)

您需要使用float函数转换字符串。您实际上并没有递增totaltotal2,而是在每个值处分配它们。

这应该做你想要的:

def main():
    print("This program will read the file and calculate the total and average of each column of  numbers")
    filename= input("\nWhat is the name of the file?")
    myfile = open(filename, "r")
    with open("numbers.txt") as myfile:
        count = 0
        total = 0.0
        total2 = 0.0
        for line in myfile:
            parts = line.split()
            if len(parts) > 1:
                total += float(parts[0])
                total2 += float(parts[1])
                count += 1
        print(total)
        print(total2)
        print(total / count)
        print(total2 / count)