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

求助:如何用Python 3修改文本文件中行首为2的行的末尾内容

Python3实现指定文本行修改

以下是实现需求的代码及说明:

实现步骤

  1. 读取目标文本文件的所有内容
  2. 逐行检查:若行首字符为2,将该行最后两个字符替换为12
  3. 将处理后的内容重新写入原文件

完整代码

# 定义文件名
file_name = "data.txt"

processed_lines = []
# 读取文件并处理每行
with open(file_name, 'r', encoding='utf-8') as input_file:
    for line in input_file:
        # 记录行是否包含换行符
        has_newline = line.endswith('\n')
        # 去除换行符处理内容
        content = line.rstrip('\n')
        
        if content.startswith('2'):
            # 替换最后两个字符为12
            content = content[:-2] + '12'
        
        # 恢复换行状态并加入结果列表
        if has_newline:
            processed_lines.append(content + '\n')
        else:
            processed_lines.append(content)

# 将处理后的内容写入文件
with open(file_name, 'w', encoding='utf-8') as output_file:
    output_file.writelines(processed_lines)

代码说明

  • 使用with语句操作文件,无需手动关闭文件,避免资源泄漏
  • 保留原始行的换行状态,避免处理后出现多余空行或丢失换行
  • 通过字符串切片[:-2]快速获取除最后两个字符外的内容,拼接12完成替换
  • 最后用writelines批量写入处理后的行,比逐行写入效率更高

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 07:55:28