如何用Python的JSON实现带登录功能的日记程序用户信息持久化
Fixing Persistent User Accounts with JSON for Your Diary App
Got it, let's sort out that account persistence problem! Right now, your user accounts live only in memory (those name and password lists), so they vanish as soon as you close the program. JSON is the perfect tool here—it lets us save user data to a file in a structured, easy-to-read format that we can reload every time the app starts up.
Here's the revised code with JSON-based persistence:
import json # Load existing users from JSON file, or start with empty dict if file doesn't exist try: with open("users.json", "r") as f: users = json.load(f) except FileNotFoundError: users = {} diary = "" x = "" namee = "" passwordd = "" print("Welcome to the Diary App!") while x != "q": print("1) Enter :1 to sign in!") print("2) Enter :2 to create a new account!") print("3) Enter :q to exit!") x = input("What would you like to do?\n").strip().lower() if x == "1": namee = input("Enter your username: ").strip() passwordd = input("Enter your password: ").strip() # Check if user exists and password matches if namee in users and users[namee] == passwordd: print(f"Welcome back, {namee}!") # Write diary entry to user.txt (kept your original logic here) with open("user.txt", "a") as file: file.write("\n\n\n\n") file.write(namee) file.write("\n\n") diary = input("Write your diary entry:\n") file.write(diary) print("Diary entry saved!") else: print("Invalid username or password. Please create an account first if you're new.") elif x == "2": namee = input("Enter your desired username: ").strip() if namee in users: print("Sorry, that username is already taken!") else: passwordd = input("Enter your password: ").strip() users[namee] = passwordd # Save updated users to JSON file with open("users.json", "w") as f: json.dump(users, f, indent=4) print("Account created successfully!") elif x == "q": print("Thank you for using the Diary App. Goodbye!") else: print("Please enter a valid option: 1, 2, or q.") print("Thanks for stopping by!")
Key Changes Explained:
- Added
jsonmodule: Python's built-in tool for reading/writing JSON data—no extra installs needed. - Loaded users on startup: We try to read
users.jsonwhen the program starts. If the file doesn't exist (first run), we start with an empty dictionary. - Replaced lists with a dictionary: Using a dict (
users) where usernames are keys and passwords are values makes validation way simpler—no more checking list indices! - Saved users immediately: Every time a new account is created, we write the updated
usersdict back tousers.json, so data persists across restarts. - Cleaner file handling: Used
withstatements for both JSON and diary files—this automatically closes files for us, avoiding accidental resource leaks.
Now when you restart the program, all existing accounts will be loaded from users.json, so users don't have to re-create their accounts every time!
内容的提问来源于stack exchange,提问作者Sherif Elshamaa
相关产品推荐
相关产品推荐

