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

Python中向账号存储文件追加记录时自动计数编号的实现方法

实现步骤与修正代码

核心逻辑

要实现追加行自动计数编号,只需在每次写入新账号前统计已有有效数据行数,新行号为已有行数+1,同时修正原代码中的语法/逻辑错误即可:

  • 先判断文件是否存在,不存在则先写入带#标记的表头
  • 每次新增前读取所有内容计算当前已有数据条数,得到新行号
  • 写入时将行号作为第一列拼接进内容即可

完整可运行代码

import os

def formatStr(s):
    nochars = 15
    return s + (" " * (nochars - len(s)))

def add_account():
    acc = input("Enter the name of your account:")
    username = input(f"Enter the username of your {acc}:")
    password = input(f"Enter the password of your {acc}:")
    ask = input(f"Do you like to save {acc} credentials? Y|N:")

    if ask.strip().upper() == "Y":
        line_num = 1
        # 处理表头和行号计算
        if os.path.exists("myfile.txt"):
            with open("myfile.txt", "r", encoding="utf-8") as f:
                lines = [l.strip() for l in f.readlines() if l.strip()]
            if lines:
                # 减去表头行,得到已有数据行数,新行号+1
                line_num = len(lines)
        else:
            # 文件不存在,先写表头
            with open("myfile.txt", "w", encoding="utf-8") as f:
                f.write("#|Account|Username|Password\n")
        # 写入新账号
        with open("myfile.txt", "a", encoding="utf-8") as f:
            f.write(f"{line_num}|{acc}|{username}|{password}\n")

def view_account():
    if not os.path.exists("myfile.txt"):
        print("暂无保存的账号信息")
        return
    with open("myfile.txt", "r", encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            if not line:
                continue
            parts = line.split("|")
            print("".join([formatStr(p) for p in parts]))

# 调用示例
add_account()
view_account()

效果验证

运行后文件存储格式如下:

#|Account|Username|Password
1|Facebook|Name|Pass
2|Google|test|123456

打印输出时会自动按15字符宽度对齐,和要求的展示格式完全一致。

内容的提问来源于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.27 12:45:07