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

如何用Python替换文本文件每行开头的'1'为'80'

需求描述

现有文本文件内容如下:

1 0.374023 0.854818 0.138672 0.230469
0 0.939941 0.597005 0.118164 0.782552
1 0.826118 0.582643 0.347764 0.803151
1 0.503418 0.822266 0.100586 0.240885

需要将每行开头的1替换为80,其余内容保持不变,替换后效果如下:

80 0.374023 0.854818 0.138672 0.230469
0 0.939941 0.597005 0.118164 0.782552
80 0.826118 0.582643 0.347764 0.803151
80 0.503418 0.822266 0.100586 0.240885
Python实现方案

方法1:逐行判断处理(基础版)

逐行读取原文件,判断行首是否为目标字符,替换后写入新文件:

# 定义文件路径
input_path = "input.txt"
output_path = "output.txt"

with open(input_path, 'r') as in_file, open(output_path, 'w') as out_file:
    for line in in_file:
        trimmed_line = line.strip()
        if trimmed_line.startswith('1 '):
            # 替换开头的1为80,保留后续内容
            modified_line = '80 ' + trimmed_line[2:] + '\n'
        else:
            modified_line = trimmed_line + '\n'
        out_file.write(modified_line)

方法2:正则表达式匹配(精准版)

用正则确保只替换作为第一个独立字段的1,避免误替换其他位置的1:

import re

input_path = "input.txt"
output_path = "output.txt"

with open(input_path, 'r') as in_file, open(output_path, 'w') as out_file:
    for line in in_file:
        # 匹配行首的1+空格,替换为80+空格
        modified_line = re.sub(r'^1 ', '80 ', line)
        out_file.write(modified_line)

方法3:原地修改原文件(谨慎使用)

如果需要直接修改原文件,可先读取全部内容替换后写回:

file_path = "input.txt"

# 读取文件所有内容
with open(file_path, 'r') as f:
    content = f.read()

# 替换所有行首的1为80
new_content = content.replace('1 ', '80 ', content.count('1 '))

# 写回原文件
with open(file_path, 'w') as f:
    f.write(new_content)

注意:原地修改前建议备份原文件,防止数据丢失。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 19:45:43