3

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()
3
  • 5
    Call reader.next() or next(reader) 3 times! Commented Oct 29, 2013 at 7:21
  • @falsetru is right. The csv module doesn't check that all rows are the same, so you can just call next() to consume them and throw them away. Commented Oct 29, 2013 at 7:23
  • Actually, if you want the data from the extra lines, you can just read it in a line at time (and save it, if desired) and then create the csv.reader object. The current position of the file doesn't have to at its very beginning when you do this. Commented Oct 29, 2013 at 8:22

3 Answers 3

4

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

from itertools import islice
reader = islice(csv.reader(f, delimiter=","), 2, None)
Sign up to request clarification or add additional context in comments.

Comments

0

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:
    ...

Comments

0

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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.