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

Python如何实现在文件的所有冒号字符后插入换行符?

实现代码

最简版本

直接读取替换后写回,适合不需要备份的场景:

with open("code.s", "r", encoding="utf-8") as f:
    text = f.read()

# 全局替换所有冒号为冒号+换行
processed_text = text.replace(":", ":\n")

with open("code.s", "w", encoding="utf-8") as f:
    f.write(processed_text)

带备份的稳妥版本

自动备份原文件为code.s.bak,避免操作失误丢失原内容:

import os
import shutil

file_path = "code.s"
# 备份原文件
if os.path.exists(file_path):
    shutil.copy2(file_path, f"{file_path}.bak")

# 读取并处理内容
with open(file_path, "r", encoding="utf-8") as f:
    text = f.read()
processed_text = text.replace(":", ":\n")

# 写入新内容
with open(file_path, "w", encoding="utf-8") as f:
    f.write(processed_text)

处理效果

你提供的示例代码处理后会变成如下格式:

movi $1,10
beginning:
 jeq $1, $0,done
   addi $1, $1,-1
   j beginning
done:
 halt

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 16:24:01