从文件读取:TypeError:+不支持的操作数类型:'int'和'str'

时间:2019-01-06 11:20:08

标签: python

请注意-之前曾有人问过这个问题,但没有一个回答令人满意地回答了这个问题。

这是代码

    numberList = []
    for x in range(6):
        numberList.append(int(input("Enter a number: ")))

    myFile = open("challenge 37.txt", "wt") #The 'wt' meaning  the 't'ext is being 
    opened for 'w'riting.

    for nums in numberList:
        myFile.write(str(nums) + "\n")

    myFile.close()




    myFile = open("challenge 37.txt", "rt") #The 'rt' meaning the 't'ext is being 
    opened for 'r'eading.

    contents = myFile.read()
    contents = contents.strip("\n")

    print("The contents of the file are:\n" + str(contents))
    total = 0
    for nums in contents.strip("\n"):
        total = total + nums

    average = total / 6

    print("The total of your number is " + str(total) + ", and the average of those 
    numbers is " + str(average))


    myFile.close()

该程序返回错误:(TypeError:+不支持的操作数类型:“ int”和“ str”) 这是25号线的电话。任何人都可以阐明这一困境吗?这是一项作业。

谢谢。

2 个答案:

答案 0 :(得分:0)

您的内容被读取为字符串,因此您应该将其转换为int

total = total + int(nums)

答案 1 :(得分:0)

基本上,您不需要剥离数据,但需要使用“ \ n”拆分数据,这样您将获得元素列表,并且列表上的计算操作很容易。
解决方案:

contents = myFile.read()
contents = contents.split("\n")[:-1]                       #split data
print("The contents of the file are:\n" + str(contents))
total = 0
for nums in contents:                                     
    total = total + int(nums)
average = total / 6
print("The total of your number is " + str(total) + ", and the average of those numbers is " + str(average))