2017-05-13 53 views
1

這是我的代碼。我不明白爲什麼我會得到這個錯誤以及如何糾正它。 出現錯誤:totals = entrant + float(tot) 這裏是我的全碼:值錯誤:無法將str轉換爲浮點數PYTHON

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() 

在此先感謝。

+4

'tot'不是一個有效的float – Li357

+1

提供文件內容的樣品或以上 – praba230890

+0

的'print'聲明的文件只是一個第一行有20個文本文件。 –

回答

0

在您的情況下,函數read()不僅可以讀取字符20,還可以讀取附加到它的新行字符。

所以變量tot包含的值不能轉換爲數字。

嘗試

tot = tot.strip() 

使用它之前。

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

+0

@GermainLeignel這是用Python 3.6在'.txt'上測試的,只有數字'20',它的值是'ValueError:could not convert string to float:'for totals = entrant + float(tot) –

+0

。你在幹什麼?你在Windows或* nix上? – pstatix

+0

@GermainLeignel這聽起來像我們需要看看你的文件的內容。 – pstatix

相關問題