这似乎是重复的,但其他的不适用。所以我正在尝试建立一个存钱罐,但我无法弄清楚如何在使用数字时添加新线路。现在我正在使用字符串,因为它是添加新行的唯一方法。但是,当我添加这两个数字时,它会像字符串一样添加它们。例如,如果您输入5.93两次。它将打印“5.935.93”。所以,我必须将其转换为字符串,但之后我将无法添加新行。这是我的代码:
def piggybank():
file = open('piggybank.txt','r+')
money = input('How much money are you adding?')
file.write(money + '\n')
for line in file:
money += line
print("You now have:\n", money)
file.close()
在第三行,我可以赚钱浮动,但在第四行,我将无法添加新行。有人可以帮忙吗?
答案 0 :(得分:3)
您可以将money
保留为Integer
,但在撰写时,请使用%s
。此外,如果要写入文件,则需要将新变量设置为open('piggybank.txt', 'wb')
以写入文件。:
def piggybank():
filew = open('piggybank.txt','wb')
file = open('piggybank.txt','rb')
money = input('How much money are you adding?')
filew.write('%s\n' % money)
for line in file:
money += line
print("You now have:\n%s" % money)
filew.close()
file.close()
答案 1 :(得分:0)
你可以这样做:
def piggybank():
file = open('piggybank.txt','rb')
money = input('How much money are you adding?')
file.write(str(money) + "\n")
for line in file:
money += float(line.strip())
print("You now have:\n" + str(money))
file.close()
答案 2 :(得分:0)
在进行数学运算时,您可以转换为浮点数。
copies
答案 3 :(得分:0)
input()
将为您提供str
(字符串)类型对象。您需要使用str
将float
转换为float()
。通过跟踪和错误,我发现了以下solition.Refernece doc链接是strip() doc,open() doc。
def piggybank():
file = open('piggybank.txt','a') #open file for appending to the end of it.
money = input('How much money are you adding? ')
file.write(money + '\n') # Write strings to text file.
file.close()
file = open('piggybank.txt','r')
sum = float(0) # initialize sum with zero value.
for line in file:
sum += float(line.strip('\n')) # srtip '\n' and convert line from str to float.
print("You now have: %s" % sum)
file.close()