在 python 中将文本写入 .txt 文件时出错

Error writing text into a .txt file in python

我正在制作一个程序 1.创建一个文本文件 2.允许存储密码 3.允许更改密码 4.添加额外的密码 5.删除特定密码 问题出在 def delete():。我在三个单独的行中输入了三个密码:第一、第二、第三。当我选择删除密码 "second" 时,它会重新打印之前的列表,然后在最后一个密码的末尾打印新列表。

这是我的代码:

import time
def create():
    file = open("password.txt", "w")
    passwordOfChoice = input("The password you want to store is: ")
    file.write(passwordOfChoice)
    print ("Your password is: ", passwordOfChoice)
    file.close()
    time.sleep(2)
def view():
    file = open("password.txt","r")
    print ("Your password is: ",
           "\n", file.read())
    file.close()
    time.sleep(2)
def change():
    file = open("password.txt", "w")
    newPassword = input("Please enter the updated password: ")
    file.write(newPassword)
    print ("Your new password is: ", newPassword)
    file.close()
    time.sleep(2)
def add():
    file = open("password.txt", "a")
    extraPassword = input("The password you want to add to storage is: ")
    file.write("\n")
    file.write(extraPassword)
    print ("The password you just stored is: ", extraPassword)
    file.close()
    time.sleep(2)
def delete():
    phrase = input("Enter a password you wish to remove: ")

    f = open("password.txt", "r+")
    lines = f.readlines()

    for line in lines:
        if line != phrase+"\n":
            f.write(line)
    f.close()

print("Are you trying to: ",
      "\n1. Create a password?",
      "\n2. View a password?",
      "\n3. Change a previous password?",
      "\n4. Add a password?",
      "\n5. Delete a password?",
      "\n6. Exit?\n")
function = input()
print("")

if (function == '1'):
    create()
elif (function == '2'):
    view()
elif (function == '3'):
    change()
elif (function == '4'):
    add()
elif (function == '5'):
    delete()
elif (function == '6'):
    print("Understood.", "\nProgram shutting down.")
    time.sleep(1)
else:
    print("Your answer was not valid.")
    print("Program shutting down...")
    time.sleep(1)

为了显示我上面的意思,这是我的输出:

Your password is:
 first
second
thirdfirst
third

谁能告诉我如何修复我的 def delete(): 函数,使其不会重写原始数据?非常感谢!

问题在于'r+'模式。当你使用 'r+' 时,你当然可以读写,但是你可以控制你写的文件中 的位置 。 发生的事情是你读取文件,光标停留在末尾,所以当你写回它时,Python 尽职尽责地将你的新行放在文件的末尾。 有关文件方法,请参阅 the docs;您正在寻找类似 seek.

的内容