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

基于For Loop的文本文件处理:合并注释行间无注释内容

解决方案

核心思路是用临时缓冲区收集注释行之间的无注释内容,遇到注释行时先合并输出缓冲区内容,再保留注释行原样,最后处理文件末尾剩余的无注释行。

直接上可运行代码:

# 读取文件内容
with open("myfile.txt", mode='r') as f:
    lines = f.readlines()

result = []
temp_lines = []

for line in lines:
    # 仅去除行尾换行符,保留原内容的空格格式
    stripped_line = line.rstrip('\n')
    if '#' in line:
        # 缓冲区有内容时先合并输出
        if temp_lines:
            merged = ''.join(temp_lines) + '\n'
            result.append(merged)
            temp_lines = []
        # 注释行原样保留
        result.append(line)
    else:
        # 无注释行加入缓冲区等待合并
        temp_lines.append(stripped_line)

# 处理文件末尾剩余的无注释行
if temp_lines:
    merged = ''.join(temp_lines) + '\n'
    result.append(merged)

# 将处理后的内容写回文件
with open("myfile.txt", mode='w') as f:
    f.writelines(result)

代码说明

  • 用readlines()一次性读取所有行,方便批量处理
  • temp_lines作为临时缓冲区,收集需要合并的无注释行内容(已去除换行符)
  • 遇到带#的注释行时,先将缓冲区内容拼接成一行,加入结果列表后再添加注释行
  • 遍历结束后检查缓冲区,避免最后一段无注释行被遗漏
  • 用writelines()将结果写回文件,覆盖原内容

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 19:01:09