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

如何用Python复制TXT文件中的行并逐行递增其中的数字?

Python实现文本行重复并递增指定数字的需求

场景1:已知原始字符串中的数字是固定的"1"

如果目标文本行格式固定(比如ABCD1EFGH),可以直接通过分割字符串快速实现:

# 读取输入文件的目标行
with open('input.txt', 'r') as input_file:
    original_line = input_file.readline().strip()

# 设置需要重复的次数
repeat_count = 4

# 拆分原始字符串为前缀和后缀(以数字"1"为分隔符)
prefix, suffix = original_line.split('1')

# 生成递增后的所有行
output_lines = [f"{prefix}{i}{suffix}" for i in range(1, repeat_count + 1)]

# 打印结果
print('\n'.join(output_lines))

# 可选:将结果写入新文件
with open('output.txt', 'w') as output_file:
    output_file.write('\n'.join(output_lines))

场景2:通用情况(原始字符串数字不固定或为多位数)

如果原始文本中的数字可能是任意位数(比如ABCD123EFGH),用正则表达式匹配数字段更灵活:

import re

# 读取输入文件的目标行
with open('input.txt', 'r') as input_file:
    original_line = input_file.readline().strip()

# 设置需要重复的次数
repeat_count = 4

# 匹配字符串中的第一个数字段
num_match = re.search(r'(\d+)', original_line)
if num_match:
    # 提取数字段、前缀、后缀
    start_num = int(num_match.group(1))
    prefix = original_line[:num_match.start()]
    suffix = original_line[num_match.end():]
    
    # 生成递增后的行
    output_lines = [f"{prefix}{start_num + i}{suffix}" for i in range(repeat_count)]
    
    # 输出结果
    print('\n'.join(output_lines))
    
    # 可选:写入文件
    with open('output.txt', 'w') as output_file:
        output_file.write('\n'.join(output_lines))
else:
    print("错误:原始文本行中未找到数字")

说明

  • 代码中repeat_count变量可根据需求修改为你需要的重复次数。
  • 使用with open语句确保文件操作完成后自动关闭资源,避免内存泄漏。
  • 两种方案分别对应固定格式和通用格式的场景,按需选择即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 01:27:49