[英]How to fix this python program which uses txt files to read and write from
I wrote this code which is supposed to input, output and clear a file, but whenever I write to it twice in a row, the second input overrides the first does anyone know how to help? 我编写了应该输入,输出和清除文件的代码,但是每当我连续两次写入文件时,第二个输入就会覆盖第一个输入,有人知道如何提供帮助吗?
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")
That's because you have opened the file to write in w
(write) mode, which will start writing from start every time. 这是因为您已打开文件以
w
(写入)模式写入文件,该模式每次都会从头开始写入。 You need to open the file in a+
(append mode). 您需要以
a+
(附加模式)打开文件。
Replace the line (line no: 4) 更换管线(管线编号:4)
repairs = open('repairs.txt', 'w')
With: 附:
repairs = open('repairs.txt', 'a+')
For your help, this is your full working 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.')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.