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

如何将文本文件每行中间的number替换为对应行号?

解决方案

核心思路是把每行按分隔符|拆分,替换中间的number字段为递增的行号,再重新拼接成目标格式。以下是两种实用实现方式:

方式1:将结果写入新文件(推荐,避免误改原文件)

with open("test.txt", 'r') as read_file, open("output.txt", 'w') as write_file:
    line_num = 0
    for line in read_file:
        # 清理行尾换行符,跳过空行
        cleaned_line = line.strip()
        if not cleaned_line:
            continue
        line_num += 1
        # 拆分每行内容,替换中间的number字段
        segments = cleaned_line.split('|')
        segments[2] = str(line_num)
        # 拼接成目标格式并写入
        new_line = '|'.join(segments)
        write_file.write(f"{new_line}\n")

方式2:直接打印结果(用于快速预览)

如果不需要保存到文件,只是临时查看输出:

with open("test.txt", 'r') as read_file:
    line_num = 0
    for line in read_file:
        cleaned_line = line.strip()
        if not cleaned_line:
            continue
        line_num += 1
        segments = cleaned_line.split('|')
        segments[2] = str(line_num)
        print('|'.join(segments))

关键细节说明

  • 用split('|')拆分后,每行的结构是['', 'DeviceImage', '原number', 'DeviceName'],所以索引2的位置就是要替换的目标字段。
  • 加入空行判断是为了避免文件末尾的空行导致无效行号或格式错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 19:30:38