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

Python代码无法写入用户名和密码至文件的问题排查

问题分析与修复方案

原代码的核心问题

  1. 文件操作逻辑错误:仅在用户名和密码都非空时才打开文件,但如果用户先输入空值,后续输入合法内容时,f变量可能未被定义,导致写入失败;而且打开文件后未关闭,缓冲区内容可能无法及时写入磁盘。
  2. 循环逻辑冗余:外层password_check循环和内层re_enter_pass循环重复,导致流程混乱。
  3. 输入校验缺失:用户名或密码为空时没有提示,直接跳过文件打开,后续操作会触发异常。

修复后的代码

import os
from time import sleep
import maskpass

while True:
    # 获取用户名和密码,去除首尾空格
    user_name = input("Hello person, what would you like your username to be? \n").strip()
    password = maskpass.askpass(mask="").strip()
    
    # 校验用户名和密码非空
    if not user_name or not password:
        print("Username and password cannot be empty.\n")
        continue
    
    # 校验密码长度
    if len(password) < 8:
        print("Please enter a password with at least 8 characters.\n")
        continue
    
    # 用with语句自动管理文件资源,确保内容写入磁盘
    with open("User_Data.txt", "a") as f:
        f.write(f"{user_name}; {password}\n")
    
    print("Password stored.")
    sleep(2)
    os.system('cls')
    
    # 询问是否继续添加,统一转大写避免大小写判断问题
    re_enter = input("Would you like to enter a new password? (Y/N)\n").strip().upper()
    if re_enter == "N":
        break
    elif re_enter == "Y":
        os.system('cls')
    else:
        print("Invalid input, exiting...")
        break

关键修改说明

  • 用with语句打开文件,自动处理文件关闭,彻底避免资源泄漏和内容未写入的问题。
  • 合并冗余循环,用单个while True简化流程,逻辑更直观。
  • 增加用户名和密码为空的校验,并给出明确提示。
  • 对输入内容做strip()处理,避免用户输入的空格被误判为有效内容。
  • 将用户的继续选择输入转为大写,避免大小写不一致导致的判断错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 08:13:40