Python新手项目:如何将TXT文件转换为字典并实现管理员与员工登录权限管理
Hey there! Let's work through your Python login system problems step by step—converting the TXT file to a dictionary and handling role-based menu navigation are totally manageable with a few clear adjustments.
1. Efficiently Convert TXT File to a Dictionary
First, let's assume your employees.txt uses a simple comma-separated format (adjust this if your file uses a different delimiter) with fields like:
username,password,salary,role admin,admin123,0,admin john,john456,5000,employee jane,jane789,6000,employee
We'll create a function to load this into a dictionary where usernames are keys—this makes looking up user data super fast (O(1) time complexity). We'll also add a save function to write changes back to the TXT file after admins modify salaries.
def load_employee_data(file_path="employees.txt"): employee_data = {} try: with open(file_path, "r") as f: next(f) # Skip the header line for line in f: line = line.strip() if not line: continue # Split line into fields - match the order in your TXT file username, password, salary, role = line.split(",") employee_data[username] = { "password": password, "salary": float(salary), "role": role.strip() } except FileNotFoundError: # Create a new file if it doesn't exist print(f"Creating new employee data file at {file_path}...") with open(file_path, "w") as f: f.write("username,password,salary,role\n") return employee_data def save_employee_data(employee_data, file_path="employees.txt"): with open(file_path, "w") as f: f.write("username,password,salary,role\n") for username, details in employee_data.items(): # Format the line and write back to TXT line = f"{username},{details['password']},{details['salary']},{details['role']}\n" f.write(line)
2. Role-Based Menu Navigation After Authentication
Next, let's update your log_in function to return the user's role (or None if login fails). Then, we'll create separate menu functions for admins and employees, and redirect the user based on their authenticated role.
Updated Login Function
def log_in(username, password, employee_data): # Check if the username exists in our dictionary if username not in employee_data: print("Error: Username not found!") return None # Verify the password matches if employee_data[username]["password"] != password: print("Error: Incorrect password!") return None # Return the user's role if login succeeds return employee_data[username]["role"]
Menu Functions
def admin_menu(employee_data): while True: print("\n=== Admin Dashboard ===") print("1. Modify Employee Salary") print("2. Log Out") choice = input("Enter your choice (1-2): ") if choice == "1": target_user = input("Enter the employee's username to update: ") if target_user not in employee_data: print("Employee not found!") continue try: new_salary = float(input(f"Enter new salary for {target_user}: ")) employee_data[target_user]["salary"] = new_salary save_employee_data(employee_data) # Save changes to TXT print(f"Successfully updated {target_user}'s salary to ${new_salary:.2f}") except ValueError: print("Invalid input! Please enter a numeric salary.") elif choice == "2": print("Logging out of admin session...") break else: print("Invalid choice! Please try again.") def employee_menu(username, employee_data): while True: print(f"\n=== Welcome, {username}! ===") print("1. View My Salary") print("2. Log Out") choice = input("Enter your choice (1-2): ") if choice == "1": salary = employee_data[username]["salary"] print(f"Your current salary is: ${salary:.2f}") elif choice == "2": print("Logging out...") break else: print("Invalid choice! Please try again.")
Main Program Flow
Put it all together in your main function to tie everything up:
def main(): # Load employee data from TXT to dictionary first employee_data = load_employee_data() # Get login credentials from user username = input("Enter your username: ") password = input("Enter your password: ") # Authenticate and get user role user_role = log_in(username, password, employee_data) # Redirect to the correct menu if user_role == "admin": admin_menu(employee_data) elif user_role == "employee": employee_menu(username, employee_data) else: print("Login failed. Please try again.") if __name__ == "__main__": main()
Quick Tips for Your Project
- Password Security: For a real-world app, never store plain-text passwords—use a library like
bcryptto hash passwords before saving them. - Input Validation: Add checks for empty username/password inputs to make the system more robust.
- TXT Format Consistency: Make sure every line in your TXT file follows the same field order to avoid
ValueErrorwhen splitting lines.
内容的提问来源于stack exchange,提问作者Ezio

