Reputation: 2187
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!
Upvotes: 0
Views: 3294
Reputation: 7821
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
).
Upvotes: 2
Reputation: 599610
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()
Upvotes: 1