【问题标题】:How to write a floating number to a text file? (python3)如何将浮点数写入文本文件? (python3)
【发布时间】:2019-10-16 06:40:50
【问题描述】:

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

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

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

【问题讨论】:

  • 要转换为字符串,只需使用str

标签: python python-3.x


【解决方案1】:

你可以在字符串中使用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\n" % cash)

也尝试以这种方式处理您的文件:

with open("history.txt", 'a') as f:
    f.write("line to append to file")

【讨论】:

  • 这很好用。我最后只是说 f.write("%f\n" % cash) 。但是,它只输出到文本框的第一行并替换它。我试图让它逐行记录,而不是仅仅替换它。
  • 尝试使用第二个 sn-p,它以附加模式打开文件,注意 'a'。您还可以探索格式化pyformat.info 的其他可能性。
【解决方案2】:
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(str(cash))
    history.close()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-19
    相关资源
    最近更新 更多