错误文本写入到一个.txt文件在python
问题描述:
我想提出一个方案,将 1.创建一个文本文件 2.允许密码存储 3.允许密码更改 4.添加附加密码 5.删除特定密码 问题出在def delete():
。我在三条独立的线上输入了三个密码:第一,第二,第三。当我选择删除密码“秒”时,它重新打印之前的列表,然后在最后一个密码末尾打印新列表。错误文本写入到一个.txt文件在python
这里是我的代码:
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;你正在寻找像寻求。
非常感谢!是否知道如何摆脱第一个三分之一,以便该例子的结束输出只会说“第一个”和“第三个” – 2015-03-13 10:08:31
我已经完成了代码。它现在允许删除,更改,创建和查看。感谢您在此过程中的帮助! – 2015-03-14 15:30:47
没问题。过去几天无法使用SO,很高兴听到您解决了麻烦! – oldmandrum 2015-03-17 10:17:28