You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python菜单选项与对应命令关联方法咨询——文本文件内容修改菜单开发

Hey there! You’ve already got a solid start with your user management menu—great job. Let’s walk through how to tie those menu options to their actual functions using if-elif-else statements, plus I’ll add a loop so users can keep using the menu until they choose to exit (a common usability tweak you’ll want for this kind of tool).

Full Working Code
while True:
    print("User Management")
    print("1.Add new record")
    print("2.View all record")
    print("3.Search record")
    print("4.Exit")
    
    # Handle non-numeric input gracefully
    try:
        option = int(input("Enter your choice: "))
    except ValueError:
        print("Oops! Please enter a valid number between 1-4.")
        continue

    if option == 1:
        # Your add record logic, with a safer file handling tweak
        name = input("Please enter your name: ")
        email = input("Please enter your email address: ")
        # Use `with` to auto-close the file (no need for f.close()!)
        with open("user.txt", "a") as f:
            f.write(f"\n{name},{email}")
        print("Record added successfully!")
    elif option == 2:
        # Basic view all records functionality
        try:
            with open("user.txt", "r") as f:
                records = f.readlines()
                if not records:
                    print("No user records exist yet.")
                else:
                    print("\nAll User Records:")
                    for index, record in enumerate(records, start=1):
                        # Split the line into name and email (strip removes extra newlines)
                        name, email = record.strip().split(",")
                        print(f"{index}. Name: {name}, Email: {email}")
        except FileNotFoundError:
            print("No user records exist yet.")
    elif option == 3:
        # Basic search by name functionality
        search_term = input("Enter the name to search for: ").strip()
        found = False
        try:
            with open("user.txt", "r") as f:
                for record in f.readlines():
                    name, email = record.strip().split(",")
                    # Case-insensitive search for better usability
                    if name.lower() == search_term.lower():
                        print(f"Found match: Name: {name}, Email: {email}")
                        found = True
                if not found:
                    print(f"No records found for '{search_term}'.")
        except FileNotFoundError:
            print("No user records exist yet.")
    elif option == 4:
        print("Exiting program. See you later!")
        break  # Exit the loop and end the program
    else:
        print("Invalid choice! Please pick a number from 1 to 4.")
Key Breakdown of What’s Added
  • if-elif-else Binding: Each menu option gets its own block. When the user enters a number, the code checks which option matches and runs the corresponding logic—exactly what you needed for linking option 1 to your add record code.
  • Loop for Reuse: The while True loop keeps the menu popping up until the user selects 4 (we use break to exit the loop here). Without this, the program would end right after one action.
  • Safer File Handling: I swapped your manual f.close() for a with statement. Python automatically closes the file when the with block ends, so you don’t have to worry about forgetting to close it or file corruption from unexpected crashes.
  • Error Handling: We catch cases where the user enters a non-number (like a letter) or when the user.txt file doesn’t exist yet—this stops the program from crashing and gives helpful feedback.

This implementation gives you a fully functional user management tool that you can expand further if you want!

内容的提问来源于stack exchange,提问作者AvgLurker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 18:07:53