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

Python实现TXT文件密码存储及已存在用户密码替换问题排查

解决TXT文件中替换用户密码时出现异常行的问题

我看到你遇到了在替换已存在用户密码时,文件里出现异常空用户名行的问题,这是因为你当前用字符串替换的方式只修改了用户名部分,没有处理整行的结构。咱们一步步来修复这个问题:

问题根源分析

你现在用s.replace(number,'%s:%s\n'%(number,newpw))的方式修改密码,这个操作只是把文本中的用户名字符串替换成新的"用户名:新密码",但原行的结构是"用户名:旧密码",替换后会把原行拆成两行(或者留下多余的旧密码部分)——比如原行8180324:flavio会被拆成8180324:pedroooo和:flavio,这就是你看到的异常内容。

另外代码里还有几个小问题:

  • 变量名不统一(函数里用了numeroaluno但外部输入的是number)
  • while循环没有处理用户输入n的情况,会无限循环
  • with语句里手动调用file.close()是多余的(with会自动管理文件生命周期)

修正后的完整代码

def registo():
    found = False
    # 先读取所有账户行到列表,方便精准修改
    accounts = []
    try:
        with open("Accounts.txt", "r") as file:
            accounts = file.readlines()
    except FileNotFoundError:
        # 首次运行文件不存在时,初始化空列表
        pass

    # 检查用户是否存在,记录目标行的索引
    user_index = -1
    for idx, line in enumerate(accounts):
        line = line.strip()
        if not line:
            continue
        user, pw = line.split(":")
        if number == user:
            print("User already exists")
            found = True
            user_index = idx
            break

    if found:
        while True:
            changepw = input("Change user password?[s/n] ").strip().lower()
            if changepw == "s":
                newpw = input("Insert new password: ").strip()
                # 直接替换目标行的完整内容
                accounts[user_index] = f"{number}:{newpw}\n"
                # 重新写入所有行到文件
                with open("Accounts.txt", "w") as file:
                    file.writelines(accounts)
                print("Password updated successfully!")
                break
            elif changepw == "n":
                print("No changes made.")
                break
            else:
                print("Invalid input, please enter 's' or 'n'.")
    else:
        # 新增用户,追加到文件末尾
        with open("Accounts.txt", "a") as file:
            account = f"{number}:{password}\n"
            file.write(account)
            print('Saved!')

number = input("Insert username: ").strip()
password = input("Insert password: ").strip()
registo()

关键改进说明

  1. 精准控制每行内容:把文件所有行读取到列表中,找到目标用户的行后直接替换整行,彻底避免字符串替换带来的意外拆分问题。
  2. 完善输入处理:while循环会持续提示直到用户输入s或n,同时用strip()和lower()处理输入的空格和大小写,提升鲁棒性。
  3. 处理文件不存在场景:用try-except捕获FileNotFoundError,确保首次运行程序时能正常创建文件。
  4. 修复变量名错误:统一使用number作为用户名变量,避免未定义变量报错。

现在运行程序,替换已存在用户的密码时,文件中对应的行会被直接更新为用户名:新密码,不会再出现异常的空用户名行,新增用户也会正常追加到文件末尾。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 08:10:17