2017-04-23 3 views
0

私はこのコードを入力して出力しクリアすると思いますが、2回連続して書き込むたびに2番目の入力がまず誰も助ける方法を知っていますか?txtファイルを使って読み書きするこのpythonプログラムを修正するには

あなたが最初から毎回の書き込みを開始します w(書き込み)モードで書き込むようにファイルを開いているためだ
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") 

答えて

0

a+(追加モード)でファイルを開く必要があります。で

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

は行(4行なし):交換してくださいあなたの助けのために

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

を、これはあなたの完全な作業コードです。

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

は、私は申し訳ありませんが、それはあなたがそれぞれのif節の最後にファイルをクローズする必要があるので、あなたは、同様にあなたのファイルを閉じていなかった –

+0

@VictorRadoslavovを動作しませんでした。 –

+0

@VictorRadoslavov、それを見て、私は私の答えを更新しました。 –

関連する問題