python read_csv读列名_如何使用Python读取CSV文件的标题列?

在处理大量大型CSV文件时,如何只读取头部行而不加载整个文件?可以使用Pandas的`pd.read_csv`获取列名,但这种方法会读取整个文件。另一种方法是使用csv模块的`DictReader`,但同样不理想。为了解决这个问题,可以利用`iglob`搜索CSV文件,并通过集合更新来获取唯一的列名,避免读取整个文件。
摘要由CSDN通过智能技术生成

I am looking for a a way to read just the header row of a large number of large CSV files.

Using Pandas, I have this method available, for each csv file:

>>> df = pd.read_csv(PATH_TO_CSV)

>>> df.columns

I could do this with just the csv module:

>>> reader = csv.DictReader(open(PATH_TO_CSV))

>>> reader.fieldnames

The problem with these is that each CSV file is 500MB+ in size, and it seems to be a gigantic waste to read in the entire file of each just to pull the header lines.

My end goal of all of this is to pull out unique column names. I can do that once I have a list of column headers that are in each of these files.

How can I extract only the header row of a CSV file, quickly?

解决方案

I've used iglob as an example to search for the .csv files, but one way is to use a set, then adjust as necessary, eg:

import csv

from glob import iglob

unique_headers = set()

for filename in iglob('*.csv'):

with open(filename, 'rb') as fin:

csvin = csv.reader(fin)

unique_headers.update(next(csvin, []))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值