如何将浮点数写入文本文件? (python3)

问题描述 投票:0回答:1

我是Python3的新手,我已经开始研究程序。这是一个财务计算器。我正在使用浮点数(用于美元和美分)。我有一个单独的.txt文档(history.txt),程序在整个代码中都引用该文档。首先,要拿走用户的钱并将其保存到文本文件中。

我尝试使用file.write()命令,但是它说参数必须是str,而不是浮点数。

import os
cash = float(input("How much cash did you earn?"))
history = open("history.txt","w+")
if os.stat("history.txt").st_size == 0:
    history.write(cash)

TypeError:write()参数必须为str,而不是float

python python-3.x
1个回答
0
投票

您可以使用字符串中的format

import os
cash = float(input("How much cash did you earn?"))
history = open("history.txt","w+")
if os.stat("history.txt").st_size == 0:
    history.write("%f" % cash)
© www.soinside.com 2019 - 2024. All rights reserved.