如何通过用户输入提取密码管理器文本文件中的特定账号数据?
Fixing Your Password Manager: A Step-by-Step Solution
Hey there! Let's break down how to build a working password manager that meets your needs, while fixing the kinks in your current code. I'll keep things simple and explain each part so you can follow along.
First, Let's Talk About the Issues in Your Current Code
- Unnecessary Global Variables: You don't need
globalhere—functions should return values you use directly, instead of relying on global state. This makes your code cleaner and easier to debug. - Misused Classes: Creating a class named after each website isn't the right approach. We can use simple dictionaries to store each entry's data, which is way more straightforward.
- Broken File Handling: You opened the file at the start but closed it mid-loop, and never actually wrote any data to it. We'll fix this with proper file read/write logic.
- Incorrect Action Parsing: Checking
action == "access" + titlewon't work because users will type something likeaccess Google. We need to split the input into a command and a website name.
Working Implementation (With Comments!)
Here's a complete, beginner-friendly version that does exactly what you need:
import json def save_password(website, username, password): """Save a new password entry to the text file""" # Use a dictionary to group all data for one website entry entry = { "website": website, "username": username, "password": password } # Open the file in append mode (so we don't overwrite existing entries) # Using `with` ensures the file closes automatically—no need for manual close() with open("Passvault.txt", "a") as vault: # Convert the dictionary to a JSON string (easy to read/write) json.dump(entry, vault) vault.write("\n") # Add a newline to separate entries def get_password(website): """Find and return a password entry by website name""" try: # Open the file in read mode with open("Passvault.txt", "r") as vault: # Loop through each line (each line is one entry) for line in vault: # Convert the JSON string back to a dictionary entry = json.loads(line.strip()) # Check if the website matches (case-insensitive for convenience) if entry["website"].lower() == website.lower(): return entry # If no matching entry was found return None except FileNotFoundError: # If the file doesn't exist yet (no entries saved), return None return None def main(): print("Welcome to Your Password Manager!") while True: action = input("\nWhat do you want to do? (Type 'new' to add, 'access [website]' to retrieve, 'quit' to exit): ").strip() if action.lower() == "quit": print("Goodbye!") break elif action.lower().startswith("new"): # Collect input for the new entry website = input("Enter website name: ").strip() username = input("Enter username: ").strip() password = input("Enter password: ").strip() # Save the entry to the file save_password(website, username, password) print(f"Successfully saved entry for {website}!") elif action.lower().startswith("access"): # Split the input into command and website name (e.g., "access Google" → ["access", "Google"]) parts = action.split(maxsplit=1) if len(parts) < 2: print("Oops, missing website name! Usage: access [website name]") continue website = parts[1].strip() entry = get_password(website) if entry: print(f"\nFound entry for {entry['website']}:") print(f"Username: {entry['username']}") print(f"Password: {entry['password']}") else: print(f"No entry found for {website}.") else: print("Invalid command. Try 'new', 'access [website]', or 'quit'.") # Run the main function when the script starts if __name__ == "__main__": main()
Key Concepts Explained
- Dictionaries: We use dictionaries to bundle website, username, and password together—this makes it easy to store and retrieve all details for a single entry.
- JSON Serialization:
json.dump()turns dictionaries into strings (to save in a file), andjson.loads()turns those strings back into dictionaries (to read from the file). This is simpler than parsing raw text manually. withStatements: Usingwith open(...)handles file closing automatically, so you don't have to worry about forgettingclose()or causing file errors.- Input Parsing: For the
accesscommand, we split the user's input to extract the website name, so users can type natural commands likeaccess Twitter.
How to Test It
- Run the script.
- Type
newand enter a website, username, and password—this adds it toPassvault.txt. - Type
access [website name]to pull up the saved entry. - Type
quitto exit the program.
This code is easy to extend too—later you could add features like editing entries, deleting them, or encrypting the file as you learn more about Python!
内容的提问来源于stack exchange,提问作者user13198001
相关产品推荐
相关产品推荐

