'myFile.write(item+"\n") TypeError: unsupported operand type(s) for +: 'int' and 'str'
Getting error:
myFile.write(item+"\n") TypeError: unsupported operand type(s) for +: 'int' and 'str'
and not sure why. Where shall I add the int
? This is my code
#comment program to create a list in a file
numberList = []
for counter in range (1,7):
number = int(input("choose a number")) #asks user to enter 6 numbers
numberList.append(number) #stores the numbers in a list
#writes numbers to a file
myFile = open('numbers.txt','w')
for item in numberList:
myFile.write(item+"\n")
myFile = open('numbers.txt','rt')
contents = myFile.read()
print(contents)
numSum = sum(numberList)
print(numSum)
sumTimesSum = sum * sum
average = SumTimesSum / 6
print(average)
myFile.close()
Solution 1:[1]
numberList
is a list of int
and when you write to a text file, you must convert it to string
, so:
for item in numberList:
myFile.write(str(item)+"\n")
Or without using for
loop
s = '\n'.join(map(str, numberList))
myFile.write(s)
Solution 2:[2]
It's literally trying to add the string and the number (i.e. 1 + 2 = 3
, "abc" + 1 = ???
). You need to convert the number to a string.
myFile.write(str(item) + "\n")
You could also use string formatting.
myFile.write("%d\n" % item)
Solution 3:[3]
I believe that you need to make item
a string.
myFile.write(+str(item)+"\n")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Iron Fist |
Solution 2 | timtim17 |
Solution 3 | interstellar |