Reputation: 295
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
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
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
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