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

如何在Python中读取并查看文本文件内的新增账号信息

实现新增账号查看功能方案

先修正现有新增代码的已知问题

你的原始代码存在2处可优化/修复点:

  • 判断条件误用了不存在的变量new_ask,实际你定义的用户输入变量是ask
  • with open上下文管理器会自动回收文件句柄,无需手动调用close()方法

修正后同时支持记录本次新增账号的代码如下:

# 存储本次运行新增的账号,用于后续查看
added_accounts = []

def Add_account():
    account = input("\nEnter the name of the account: ")
    username = input(f"Enter the username of your {account}: ")
    password = input(f"Enter the password of your {account}: ")
    ask = input(f"Do you want to save {account} credentials? [Y|N]: ")

    if ask == "Y":
        # 先把明文存入本次新增列表,后续输出用
        added_accounts.append((account, username, password))
        with open("info.txt", "a") as file:
            file.write("\n" + encrypt(account) + ":" + encrypt(username) + ":" + encrypt(password))
         
Add_account()

实现新增账号对齐输出功能

你可以直接读取刚才记录的added_accounts列表,用字符串格式化控制对齐输出即可,示例代码如下:

def display_added_accounts():
    # 先打印表头,<表示左对齐,数字为字段占用宽度,可根据实际需求调整
    print(f"{'No.':<6}{'Account Name':<20}{'Username':<20}{'Password'}")
    for idx, (account, username, password) in enumerate(added_accounts, start=1):
        print(f"{idx:<6}{account:<20}{username:<20}{password}")

# 新增完成后调用即可查看本次新增内容
display_added_accounts()

如果你需要跨会话查询历史新增账号

如果需要程序重启后依然能筛选某个时间点之后的新增账号,你可以在写入账号时额外存储加密的时间戳:

  1. 写入格式调整为加密(时间戳):加密(账号名):加密(用户名):加密(密码)
  2. 查询时先指定起始时间,读取文件所有行,解密每行的时间戳,筛选出大于起始时间的记录,再按上面的格式化方式输出即可

注意:你需要自行实现和encrypt对应的decrypt解密函数,用于读取加密后的存储内容

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 08:54:03