如何用Python拆分含重复列名的大型CSV文件?
用Python拆分含重复列名的大型CSV文件
完全可以实现,针对大型文件,我们采用逐行读取的方式避免内存溢出,下面是具体代码和逻辑说明:
代码实现
input_file = "large_data.csv" # 替换为你的输入文件路径 output_prefix = "split_file_" # 输出文件前缀,可自定义 # 读取第一行作为列名模板,自动适配你的CSV列名 with open(input_file, 'r', encoding='utf-8') as f: header_template = f.readline().strip() file_index = 1 current_data_block = [header_template] # 逐行处理大文件 with open(input_file, 'r', encoding='utf-8') as f: next(f) # 跳过已读取的第一行 for line in f: cleaned_line = line.strip() # 检测到重复列名行时执行拆分 if cleaned_line == header_template: # 将当前数据块写入独立文件 with open(f"{output_prefix}{file_index}.csv", 'w', encoding='utf-8') as out_file: out_file.write('\n'.join(current_data_block) + '\n') # 重置数据块,开始新分组 current_data_block = [cleaned_line] file_index += 1 else: # 非列名行加入当前数据块 current_data_block.append(cleaned_line) # 处理最后一组未写入的数据 if current_data_block: with open(f"{output_prefix}{file_index}.csv", 'w', encoding='utf-8') as out_file: out_file.write('\n'.join(current_data_block) + '\n')
关键逻辑说明
- 自动适配列名:读取文件第一行作为列名模板,无需硬编码列名,兼容不同CSV结构
- 低内存消耗:逐行读取文件,不会一次性加载整个大文件到内存,适合处理几十GB级的大型CSV
- 拆分触发机制:每遇到与列名模板完全匹配的行,就将积累的数据写入新文件,然后开启新的数据块
- 收尾处理:循环结束后,将最后一组未保存的数据写入最终文件
注意事项
- 若列名行存在空格、换行符等细微差异,可修改判断逻辑,比如将行内容按逗号分割后比较列名列表
- 若CSV使用非UTF-8编码(如GBK),需将代码中的
encoding='utf-8'替换为对应编码 - 输出文件命名为
split_file_1.csv、split_file_2.csv...,可通过修改output_prefix自定义文件名前缀
内容的提问来源于stack exchange,提问作者npool
相关产品推荐
相关产品推荐

