我正在做一项任务,我必须在那里进行公寓注册计划。我在文本文件中保存了这样的公寓信息:
['B01','3','Master: TP_1','TP_2','TP_3']
['B02','2','Master: TP_1','TP_2','TP_3']
['B03','1','Master: TP_1','TP_2','TP_3']
['B04','0','Master: TP_1','TP_2','TP_3']
['B05','1','Master: TP_1','TP_2','TP_3']
['B06','2','Master: TP_1','TP_2','TP_3']
['B07','3','Master: TP_1','TP_2','TP_3']
['B08','2','Master: TP_1','TP_2','TP_3']
['B09','1','Master: TP_1','TP_2','TP_3']
['B10','0','Master: TP_1','TP_2','TP_3']
现在,每当新学生注册到公寓时,我想在占用者数量上加1,这是列表中的第二个值。我还想用学生证号码替换TP。
def apartmentRegister(): #REGISTERING APARTMENT
AorB=input("Would you like to register into Apartment A or B? (A/B)")
if AorB==("A") or AorB==("a"):
room=input("Insert room number: ")
f=open("Apartment_A.txt", "r")
for line in f.readlines():
if not line or line =="\n":
continue
A_register=literal_eval(line)
if A_register[-5]==(room):
if A_register[-3]==("TP_1"):
f=open("Apartment_A.txt", "a")
TPagain=input("Please input your TP number: ")
new=line.replace("TP_1",TPagain)
f.write(new+"\n")
print("You're all set")
f.close()
elif AorB==("B") or AorB==("b"):
room=input("Insert room number: ")
g=open("Apartment_B.txt", "r")
for line in g.readlines():
if not line or line =="\n":
continue
B_register=literal_eval(line)
if B_register[-5]==(room):
if B_register[-3]==("Master: TP_1"):
g=open("Apartment_B.txt", "a")
TPagain=input("Please input your TP number: ")
new=line.replace("TP_1",TPagain)
g.write(new+"\n")
print("You're all set")
g.close()
整个代码可以工作......只是因为我无法替换我想要替换的值/文本...相反,它会在文本文件中添加一个新行。
答案 0 :(得分:1)
你可能想要这些内容:
# This is the content of the file after processing
new_contents_A = []
# Read in all lines and save them to the list
with open("Apartment_A.txt", "r") as f:
for line in f.readlines():
if not line or line =="\n":
new_contents_A.append(line)
continue
A_register=literal_eval(line)
if A_register[-5]==room and A_register[-3]==("TP_1"):
TPagain=input("Please input your TP number: ")
new=line.replace("TP_1",TPagain)
new_contents_A.append(new)
else:
new_contents_A.append(line)
# Override the file with the now changed data
with open("Apartment_A.txt", "w") as f:
for line in new_contents_A:
f.write(line)