Python 替换textfile中列表中的文本
我目前正在做一项任务,我必须做一个公寓登记程序。我将公寓信息保存在一个文本文件中,如下所示:Python 替换textfile中列表中的文本,python,python-3.x,Python,Python 3.x,我目前正在做一项任务,我必须做一个公寓登记程序。我将公寓信息保存在一个文本文件中,如下所示: ['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'
['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,这是列表中的第二个值。我还想用学生ID号替换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()
整个代码工作正常。。。只是我无法替换我要替换的值/文本。。。相反,它会在文本文件中添加一行新内容。您可能需要以下内容:
# 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)
您可以使用
open(filename,“a”)
打开文件,其中a
表示结尾处的append(请参阅)。您更希望打开它,读取所有行,相应地更改行,然后保存覆盖整个文件的所有行。我先用“r”打开,然后用“a”,这就是问题所在当你打开文件时,你应该检查r
、a
或w
所做的事情。除了代码中的错误,干净的方法是使用CSV文件或小型数据库。