我正在尝试制作一个程序来保存密码。如何获取输入并将其放入文本文件password.txt?另外我将来如何检索这些数据并打印出来?
def display():
print ("Do you want to add a password to get a password? get/add")
response = input()
if response == "get":
savingPasswords()
def savingPasswords():
username = input("Enter username")
username = open ('password.txt', 'w')
password = input ("Enter password")
account = input("What account is this for?")
print ("Login successfully saved!")
while status == True:
display()
写入文件:
password="my_secret_pass"
with open("password.txt","w") as f:
f.write(password)
要从文件中读取密码,请尝试:
with open("password.txt","r") as f:
password = f.read()
问题出在您的第二个功能上。我建议使用open来打开和写入文件,因为它看起来更干净并且更易于阅读。在您的代码中,您从未关闭过文件。执行缩进块后,with open方法将为您关闭文件。我也建议写入诸如csv文件之类的东西,以获得诸如此类的组织信息,以便以后更容易检索。
def saving_passwords():
with open('password.csv', 'a') as f:
username = input("Enter username: ")
password = input("Enter password: ")
account = input("What account is this for? ")
f.write(f"{username},{password},{account}\n") # separates values into csv format so you can more easily retrieve values
print("Login successfully saved!")