Eric
Eric

Reputation: 295

python csv headers not in first line

I have a csv file deliminated by ,. The first line contains the report name, the second line contains the report data. The headers are in line 3 and all the other rows are data. How do I use the csv module to read the headers from line 3 instead of 1? Below is what I have now.

import csv
f = open ("myfile.csv", "rb")
reader = csv.reader(f, delimiter=",")
headers = reader.next()

Upvotes: 3

Views: 3889

Answers (3)

roschach
roschach

Reputation: 9336

Maybe you could iterate until you get the desired line:

import csv
headerLine = 3
f = open ("myfile.csv", "rb")
reader = csv.reader(f, delimiter=",")
for ii in range(0, headerLine):
    headers = reader.next()

Upvotes: 0

Janne Karila
Janne Karila

Reputation: 25197

You can use itertools.islice to discard items from an iterator.

from itertools import islice
reader = islice(csv.reader(f, delimiter=","), 2, None)

Upvotes: 4

Dzinx
Dzinx

Reputation: 57804

If your file is not very large, you can just read everything and discard the first two lines later:

with file("myfile.csv", "rb") as f:
    reader = csv.reader(f, delimiter=',')
    lines = list(reader)[2:]
headers, value_rows = lines[0], lines[1:]
for row in value_rows:
    ...

Upvotes: 0

Related Questions