值错误:无法将str转换为浮点PYTHON

时间:2017-05-13 16:13:53

标签: python

这是我的代码。我不知道为什么我会收到此错误以及如何纠正错误。 错误显示在:totals = entrant + float(tot) 这是我的完整代码:

def total():
    File = open("argent.txt","r")
    File = File.read()
    tot = File
    print("You have",tot,"£ in your account")

def add():
    entrant = float(input("How many do you want to add to your account? "))

    with open("argent.txt", 'r') as f:
        tot = f.read().rstrip('\n')

    print("You have ",tot,"£ in your account")
    totals = entrant + float(tot)
    print(totals)

    with open("argent.txt", 'w') as f:
        output = str(totals)
        f.write(output)
add()

提前致谢。

2 个答案:

答案 0 :(得分:0)

在您的情况下,函数read()不仅会读取字符20,还会读取附加到其上的新行字符。

因此变量tot包含不可转换为数字的值。

尝试

tot = tot.strip()

使用前。

答案 1 :(得分:0)

将来,请尝试避免将File用于file type变量。

entrant = float(input("How many do you want to add to your account? "))

with open("argent.txt", 'r') as f:
    tot = f.read().rstrip('\n')

print("You have ",tot,"£ in your account")
totals = entrant + float(tot)
print(totals)

with open("argent.txt", 'w') as f:
    output = str(totals)
    f.write(output)

通过使用with open,文件在以下代码后关闭。

修改:修正了从'w'float的文件输出str