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

如何提取CSV文件表头并写入另一文件?大列数场景表头截断问题排查

处理CSV表头:提取写入+解决大列数截断问题

我来帮你搞定这两个CSV处理的问题,先从基础的表头提取说起,再解决大列数导致的输出截断异常:

1. 从CSV文件提取表头并写入另一个文件

用Python内置的csv模块就能轻松实现,这个模块处理CSV文件稳定且无需额外安装依赖。直接上可运行的代码:

import csv

# 读取源CSV的表头
with open('source.csv', 'r', newline='', encoding='utf-8') as source_file:
    csv_reader = csv.reader(source_file)
    header_row = next(csv_reader)  # 读取第一行即表头

# 将表头写入新文件
with open('header_result.csv', 'w', newline='', encoding='utf-8') as output_file:
    csv_writer = csv.writer(output_file)
    csv_writer.writerow(header_row)

小细节说明:

  • newline=''是为了避免Windows系统下写入CSV时出现多余空行;
  • 指定encoding='utf-8'能防止中文或特殊字符乱码;
  • 如果你的CSV用制表符/其他分隔符,记得在csv.reader和csv.writer里添加delimiter='\t'这类参数适配。

2. 解决200+列CSV表头输出截断的问题

你遇到的屏幕输出截断,本质是Python默认的打印逻辑会对过长列表进行换行或截断显示——实际上代码读取的表头是完整的,只是显示环节看不到全部。这里给你两种实用解决办法:

方法一:用pprint强制完整显示

pprint是Python的漂亮打印模块,通过设置宽度参数就能让所有列完整输出:

import csv
import pprint

with open('large_columns.csv', 'r', newline='', encoding='utf-8') as source_file:
    csv_reader = csv.reader(source_file)
    header_row = next(csv_reader)

# 设置足够大的width值,确保所有表头列都能显示
pprint.pprint(header_row, width=2000)

方法二:转成字符串输出

直接将表头列表用逗号(或你需要的分隔符)拼接成字符串,打印出来就是完整的一行:

import csv

with open('large_columns.csv', 'r', newline='', encoding='utf-8') as source_file:
    csv_reader = csv.reader(source_file)
    header_row = next(csv_reader)

# 用逗号分隔表头,完整输出
print(', '.join(header_row))

如果你用Pandas处理CSV:

如果是用Pandas读取,默认也会截断列显示,只需修改Pandas的显示配置:

import pandas as pd

# 让Pandas显示所有列,不截断
pd.set_option('display.max_columns', None)
pd.set_option('display.width', 2000)

df = pd.read_csv('large_columns.csv')
print(df.columns.tolist())

注意:不管列数多少,用csv.writer或Pandas写入文件的表头都是完整的,截断只发生在屏幕输出环节,所以写入文件的逻辑不需要调整。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 08:15:14