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

Python密码管理器开发:如何删除指定用户名的全部关联账户信息?

解决方法

你的问题核心在于每个账户是完整的块结构(分隔线+用户名+密码+网站+分隔线+空行),仅删除用户名所在行无法移除整个账户的关联信息。需要识别并删除整个账户块,具体实现如下:

1. 新增删除账户函数

添加delete_account函数,通过识别账户块的分隔标记,过滤掉目标用户名对应的完整块,再将剩余内容写回文件:

def delete_account():
    target_username = input("Enter the username to delete: ")
    # 读取文件所有行内容
    with open("info.txt", "r") as f:
        lines = f.readlines()
    
    new_content = []
    skip_block = False
    # 遍历每行,识别并跳过目标账户块
    for line in lines:
        stripped_line = line.strip()
        # 遇到分隔线,判断是否进入/退出目标块
        if stripped_line == "----------------------------------":
            if skip_block:
                # 结束跳过目标块
                skip_block = False
                continue
            # 先暂存分隔线,检查下一行的用户名
            new_content.append(line)
            idx = lines.index(line)
            if idx + 1 < len(lines):
                username_line = lines[idx+1]
                if f"Username: {target_username}" in username_line:
                    # 匹配到目标账户,标记跳过整个块
                    skip_block = True
                    new_content.pop()  # 移除刚添加的分隔线
                    continue
        # 非跳过状态的行,保留到新内容中
        if not skip_block:
            new_content.append(line)
    
    # 将过滤后的内容写回文件
    with open("info.txt", "w") as f:
        f.writelines(new_content)
    print(f"Account with username '{target_username}' deleted successfully!")

2. 修改主循环逻辑

在主菜单的删除账户分支中调用上述函数:

elif choice == "3":
    os.system('cls')
    delete_account()

关键逻辑说明

  • 用----------------------------------作为账户块的起始/结束标记,以此识别每个账户的范围
  • 当检测到某块的用户名匹配目标时,标记skip_block为True,跳过该块的所有行(包括分隔线、用户名、密码、网站、结束分隔线及空行)
  • 使用with open语法自动管理文件关闭,比手动open/close更安全可靠

完整修改后代码

import os.path

def checkExistence():
    if not os.path.exists("info.txt"):
        with open("info.txt", "w") as file:
            pass

def appendNew():
    userName = input("Enter username: ")
    os.system('cls')
    password = input("Enter password: ")
    os.system('cls')
    website = input("Enter website: ")
    os.system('cls')

    usrnm = f"Username: {userName}\n"
    pwd = f"Password: {password}\n"
    web = f"Website: {website}\n"

    with open("info.txt", "a") as file:
        file.write("----------------------------------\n")
        file.write(usrnm)
        file.write(pwd)
        file.write(web)
        file.write("----------------------------------\n")
        file.write("\n")

def readPasswords():
    with open("info.txt", "r") as file:
        content = file.read()
    print(content)

def delete_account():
    target_username = input("Enter the username to delete: ")
    with open("info.txt", "r") as f:
        lines = f.readlines()
    
    new_content = []
    skip_block = False
    for line in lines:
        stripped_line = line.strip()
        if stripped_line == "----------------------------------":
            if skip_block:
                skip_block = False
                continue
            new_content.append(line)
            idx = lines.index(line)
            if idx + 1 < len(lines):
                username_line = lines[idx+1]
                if f"Username: {target_username}" in username_line:
                    skip_block = True
                    new_content.pop()
                    continue
        if not skip_block:
            new_content.append(line)
    
    with open("info.txt", "w") as f:
        f.writelines(new_content)
    print(f"Account with username '{target_username}' deleted successfully!")

checkExistence()

while True:
    choice = input("Do you want to: \n 1. Add account\n 2. View accounts\n 3. Delete account\n")
    os.system('cls')

    if choice == "1":
        appendNew()
    elif choice == "2":
        readPasswords()
    elif choice == "3":
        delete_account()
    else:
        print("huh? thats not an input.. Try again.\n")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 07:35:19