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

Python处理学生目录文本文件 修复首编号与行号不匹配的切片错误

问题原因

原有实现默认行首编号只有1位,固定截取line[1:]替换前缀,当原有行首编号为2位及以上时,只会删除编号的第一个数字,残留的数字会和新行号拼接,最终导致编号错误。

实现方案

核心逻辑为拆分每行第一个逗号前的所有内容作为待替换的编号段,拼接新行号和逗号后的原有内容即可,适配任意长度的原有编号,且不会修改后续字段的格式和内容。

def line_restructure():                                                                                                 
    with open("Student_Directory.txt", "r", encoding="utf-8") as f:                                                                       
        line_num = 1                                                            
        output = []
        for line in f:
            # 兼容空行场景
            if not line.strip():
                output.append(line)
                continue
            # 仅按第一个逗号拆分,保留后续所有原始内容
            _, content_suffix = line.split(',', 1)
            new_line = f"{line_num},{content_suffix}"
            output.append(new_line)
            line_num += 1
    with open("Student_Directory.txt", "w", encoding="utf-8") as f:
        f.writelines(output)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 20:24:03