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

时间:2015-03-13 09:20:22

标签: python-3.x text-files

我正在制作一个计划 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():功能,以便它不会重写原始数据吗?万分感谢!

1 个答案:

答案 0 :(得分:0)

问题在于'r +'模式。当您使用'r +'时,您可以读取和写入,当然,您可以在您编写的文件中控制 where 。 发生了什么事情是你读取文件,光标停留在最后,所以当你把它写回来时,Python尽职尽责地把你的新行放在文件的末尾。 有关文件方法,请参阅the docs;你正在寻找像寻求这样的东西。