2017-04-23 2 views
0

ich diesen Code geschrieben, der Eingabe, Ausgabe sollte und eine Datei löschen, aber wenn ich es zweimal hintereinander schreiben, überschreibt der zweite Eingang der Wer weiß zuerst wie man hilft?Wie dieses Python-Programm beheben, die txt-Dateien verwendet zum Lesen und Schreiben von

while True: 
    inorout=input("Would you like to input, output, quit or clear history?") 
    if inorout.lower() == "input": 
     repairs = open('repairs.txt', 'w') 
     customer = input('Customer: ') 
     job = input('Service: ') 
     date = input("Date(dd.mm.yyyy):") 

     if customer and job and date: 
     repairs.write('%s, %s, %s\n' %(customer, job, date)) 
     else: 
     print("Not applicable") 

Antwort

0

Das ist, weil Sie die Datei geöffnet haben in w (schreiben) Modus zu schreiben, das Schreiben beginnt jedes Mal aus starten. Sie müssen die Datei in a+ öffnen (Append-Modus).

die Linie ersetzen (Linie: 4)

repairs = open('repairs.txt', 'w') 

mit:

repairs = open('repairs.txt', 'a+') 

für Ihre Hilfe, das Ihr voller Arbeits Code.

while True: 
    inorout=input("Would you like to input, output, quit or clear history?") 
    if inorout.lower() == "input": 
     repairs = open('repairs.txt', 'a+') # <----- this line 
     customer = input('Customer: ') 
     job = input('Service: ') 
     date = input("Date(dd.mm.yyyy):") 


     if customer and job and date: 
     repairs.write('%s, %s, %s\n' %(customer, job, date)) 
     else: 
     print("Not applicable") 
     repairs.close() # <------- this line 

    elif inorout.lower() == "output": 
     repairs = open('repairs.txt', 'r') 
     selected=input("What customer do you select?") 
     output=repairs.readlines() 
     stripped_output = [] 
     for line in output: 
     stripped_output.append(line.strip()) 

     for pair in stripped_output: 
     if pair.split(', ')[0] == selected: 
      print(pair) 
     else: 
      print("Customer not found.") 
     repairs.close() # <------- this line 

    elif inorout.lower() == 'quit': 
     break 
    elif inorout.lower() == "clear history": 
     open("repairs.txt", 'w').close() 
     print("Databases successfully reset") 
    else: 
     print('Command not found.') 
+0

Es tut mir leid, aber das nicht –

+0

@VictorRadoslavov funktionierten, waren Sie Ihre Datei auch nicht schließen, so dass Sie die Datei am Ende jeder, wenn Klausel schließen müssen. –

+0

@VictorRadoslavov, dass ich meine Antwort aktualisiert haben. –

Verwandte Themen