Reputation: 25
I have a problem with my code and I just don't understand why its not working. The code:
total = 0
with open("receipt.txt", "r") as receipt:
for line in receipt:
the_line = line.split(",")
total_product = the_line[4]
total_product = total_product.translate(None, '\n')
print total_product
total += float(total_product)
with open("receipt.txt", "a") as receipt:
receipt.write("Total of Items: " + total)
The total_product when printed to console is:
5.94
807.92
2000.40
0.00
What I don't understand is why its not converting each of those to floats and instead prints error to console:
TypeError: cannot concatenate
'str'
and'float'
objects
I would love it if someone could tell me how to fix it or/and why its doing it.
Upvotes: 2
Views: 143
Reputation: 6834
Convert the total
variable which is type float
to a string
receipt.write("Total of Items: " + str(total))
Here is an example:
total = 13.54
str(total)
>> '13.54'
Upvotes: 2
Reputation: 10090
Your code actually is successfully converting each of the total_product
s to a float. The error is in the last line of your snippet where you try to concatenate your string output with the value of your total
variable (which is still a float). You should use either string formatting (recommended solution):
with open("receipt.txt", "a") as receipt:
receipt.write("Total of Items: {:.2f}".format(total))
or just cast your float to a string:
with open("receipt.txt", "a") as receipt:
receipt.write("Total of Items: " + str(total))
Upvotes: 4