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

如何用Python优雅分割含指定标识的混合格式CSV文件

Python 优雅分割CSV文件方案

可以通过计数器自动命名输出文件的方式实现,无需手动声明多个变量,核心思路是每次触发分割标记时,关闭当前输出文件并创建新文件,代码逻辑清晰简洁:

input_file_path = "你的输入文件路径.txt"
split_marker = "abc def"
file_counter = 0
current_output = None

# 读取原文件并逐行处理
with open(input_file_path, 'r', encoding='utf-8') as input_file:
    for line in input_file:
        # 去除换行符,保留行内原有格式
        line_clean = line.rstrip('\n')
        # 触发分割条件时切换输出文件
        if line_clean == split_marker:
            # 关闭之前打开的输出文件(如果存在)
            if current_output is not None:
                current_output.close()
            file_counter += 1
            # 创建新的输出文件,文件名按计数器自动生成
            output_filename = f"分割文件_{file_counter}.txt"
            current_output = open(output_filename, 'w', encoding='utf-8')
        # 将当前行写入活跃的输出文件
        if current_output is not None:
            current_output.write(line)

# 处理最后一个打开的文件,避免资源泄漏
if current_output is not None:
    current_output.close()

代码说明

  • 用file_counter自动生成输出文件名(如分割文件_1.txt、分割文件_2.txt),无需手动维护多个文件变量
  • 逐行读取原文件,遇到分割标记abc def时自动切换输出目标
  • 保留原文件的行格式(包括换行符),确保分割后的文件与原片段格式一致
  • 最后主动关闭最后一个输出文件,避免文件资源占用

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 03:35:25