我的代码有问题,我只是不明白为什么它不工作。代码:当打印到控制台不会将字符串格式的十进制数字转换为浮点数
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)
的total_product是:
5.94
807.92
2000.40
0.00
我不明白的是为什么它不把每个那些漂浮的,而是打印错误控制台:
TypeError: cannot concatenate
'str'
and'float'
objects
如果有人能告诉我如何解决这个问题,或者为什么要这样做,我会喜欢它。
请包含完整的错误消息和receipt.txt文件的内容。 – timgeb
无关:'print >> output_file,“Total Items:”,sum(float(line.split(',')[4])for line in file)' – jfs