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

Python如何匹配CSV起始标志将单个CSV拆分为多个独立CSV文件

问题处理方案

你当前得到的返回结果是'new_file'标记字符串和对应数据列表交替出现的结构,按以下步骤处理即可实现拆分生成独立CSV的需求:

步骤1:拆分返回结果为独立数据分组

import csv

# 调用你已实现的函数得到原始结果
result_list = my_func(file_name)
data_groups = []
current_group = []

# 过滤标记字符串,拆分出每个文件对应的数据集
for item in result_list:
    if item == 'new_file':
        if current_group:
            data_groups.append(current_group)
            current_group = []
    else:
        current_group.append(item)
# 补充最后一组数据
if current_group:
    data_groups.append(current_group)

步骤2:遍历分组写入CSV文件

# 序号从1开始命名文件
for idx, group in enumerate(data_groups, start=1):
    output_name = f'new_file{idx}.csv'
    # newline参数避免Windows系统下生成多余空行
    with open(output_name, 'w', newline='', encoding='utf-8') as f:
        writer = csv.writer(f)
        for row in group:
            # 可选:过滤全空数据行
            if any(cell.strip() for cell in row):
                writer.writerow(row)

可选优化方案

如果原CSV文件体积很大,不需要全量读取到内存,可直接在读取原文件时实时拆分写入,内存占用更低:

import csv

def split_csv(source_path):
    file_index = 0
    current_file = None
    current_writer = None

    with open(source_path, 'r', encoding='utf-8') as f:
        reader = csv.reader(f)
        # 跳过表头行
        next(reader)
        for row in reader:
            if row[0].strip() == 'new':
                file_index += 1
                # 关闭上一个文件句柄
                if current_file:
                    current_file.close()
                # 创建新文件
                new_path = f'new_file{file_index}.csv'
                current_file = open(new_path, 'w', newline='', encoding='utf-8')
                current_writer = csv.writer(current_file)
                continue
            # 写入有效数据行
            if current_writer:
                data_content = row[1].strip()
                if data_content:
                    current_writer.writerow([data_content])
    # 关闭最后一个文件
    if current_file:
        current_file.close()

# 直接调用即可完成拆分
split_csv('你的原CSV文件路径.csv')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 17:57:04