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

时间:2021-05-08 11:19:21

标签: 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 很陌生,所以我真的需要一些帮助来解决这个问题。

1 个答案:

答案 0 :(得分:0)

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