2017-05-13 3 views
1

Hier ist mein Code. Ich verstehe nicht, warum ich diesen Fehler bekomme und wie ich ihn korrigiere. Der Fehler tritt auf: totals = entrant + float(tot) hier ist mein vollständiger Code:Wert Fehler: konnte STR nicht in Float konvertieren 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() 

Vielen Dank im Voraus.

+4

'tot' Datei keine gültige Schwimmer ist – Li357

+1

eine Probe Ihres Dateiinhalt Bereitstellung oder die' print' Aussage über – praba230890

+0

die Datei nur ein Textdatei mit 20 in der ersten Zeile. –

Antwort

0

In Ihrem Fall die Funktion read() liest nicht nur Zeichen 20 sondern auch eine neue Linie Stelle (n) angehängt.

Also die Variable tot enthält den Wert, der nicht in eine Zahl umwandelbar ist.

Versuchen

tot = tot.strip() 

bevor Sie es.

0

In Zukunft sollten Sie vermeiden, File für file type Variablen zu verwenden.

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) 

von with open die Datei mit der Nähe nach dem folgenden Code ein.

Edit: Fest die 'w' Ausgabe von float zu str

+0

Ich bekomme "ValueError: Konnte String in Float nicht konvertieren:" für Summen = Teilnehmer + Float (tot) –

+0

@GermainLeignel Dies wurde mit Python 3.6 auf einem '.txt' mit nur der Zahl' 20' darin getestet. Womit rennst du dagegen? Bist du auf Windows oder * nix? – pstatix

+0

@GermainLeignel Es klingt, als müssten wir uns den Inhalt Ihrer Datei ansehen. – pstatix

Verwandte Themen