0

I was wondering if there was a way to only read the header info from a csv file without loading the whole file. I'm dealing with large csv files and would rather not have to load the whole thing.

Thanks!

marc
  • 2,037
  • 9
  • 24
  • 32

2 Answers2

2
with open(filename) as in_file:
    csv_reader = csv.reader(in_file)
    header = next(csv_reader)

This works because csv.reader() returns a generator, not a list. It will only output data if next() is called (i.e. by using next(csv_reader) or by using it in a for loop, like for row in csv_reader).

Community
  • 1
  • 1
Steinar Lima
  • 7,644
  • 2
  • 39
  • 40
1

You wouldn't normally read the whole file anyway. Just create the CSV reader and call next() on it once.

import csv
f = open('myfile.csv')
reader = csv.reader(f)
header = reader.next()
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895