如何将变量保存到文本文件并在以后检索?

2024-06-26 14:52:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试制作一个保存密码的程序。如何获取输入并将其放入文本文件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()


Tags: totxtadd密码inputgetresponsedef
3条回答

您可以将数据存储为json:

import json
import os

# data will be saved base on the account
# each account will have one usernae and one pass


PASS_FILE = 'password.json'

def get_pass_json_data():
    if os.path.isfile(PASS_FILE):
        with open(PASS_FILE) as fp:
            return json.load(fp)

    return {}

def get_pass():
    account = input("What account is this for?")
    data = get_pass_json_data()

    if account not in data:
        print('You do not have this account in the saved data!')

    else:
        print(data[account])

def savingPasswords():
    username = input("Enter username")
    password = input ("Enter password")
    account = input("What account is this for?")

    data = get_pass_json_data()

    # this will update your pass and username for an account
    # if already exists

    data.update({
        account: {
            'username': username,
            'password': password
        }
    })

    with open(PASS_FILE, 'w') as fp:
        json.dump(data, fp)


    print ("Login successfully saved!")

actions = {
    'add': savingPasswords,
    'get': get_pass
}

def display():
    print("Do you want to add a password to get a password? get/add")
    action = input()

    try:
        actions[action]()
    except KeyError:
        print('Bad choice, should be "get" or "add"')

while 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()

问题在于您的第二个函数。我建议使用with open来打开和写入文件,因为它看起来更干净,更易于阅读。在代码中,您从未写入文件或关闭文件。with open方法在执行缩进块后为您关闭文件。我还建议将类似csv文件的内容写入此类有组织的信息中,以便以后更容易检索

def display():
    response = input("Do you want to add a password to get a password? (get/add)\n")
    if response.upper() == "GET":
        get_password()
    elif response.upper() == "ADD":
        write_password()
    else:
        print("Command not recognized.")
        exit()


def write_password():
    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!")


def get_password():
    with open("password.csv", "r") as f:
        username = input("What is your username? ")
        lines = f.readlines()
        for line in lines:
            if line.startswith(username):
                data = line.strip().split(",")
                print(f"Your password: {data[1]}\nYour Account type: {data[2]}")


while True:
    display()

相关问题 更多 >