如何在python中覆盖文本文件中的一行文本


name email phonenumber
eric example@gmail.com 01381031
tuna tuna@gmail.com 1571051

上面是personal_details.txt

def personal(userid):
print("Modify personal details")
newemail = input("Enter your new email: ")
newphone = input("Enter your new phone:")
with open("personal_details.txt", "r+") as file:
for line in file:
line = line.split()
if userid == line[0]:
file.seek(0)
file.write(" " + newemail + " " + newphone)
file.truncate()

我正在创建配置文件系统,用户可以修改详细信息。我想覆盖文件的第[2]行和第[3]行中的文本,但它一直覆盖整个文件。我对python很陌生,所以我真的需要一些帮助来解决这个问题。

首先将文本复制到一个新变量中,并使用.replaces替换所需单词,然后可以覆盖文本文件

最新更新