Stephopolis Stephopolis - 1 year ago 129
Python Question

Skipping lines, csv Dict Reader Python

I have a file that has an obnoxious preface to the header. So it looks like this:

Review performed by:






Tab Separated Header Names That I Want To Use

I want to skip past everything and use the tab sep header names for my code. This is what I have so far:

reader = csv.DictReader(CSVFile)
for i in range(14): #trying to skip the first 14 rows
for row in reader:
if args.nextCode:
tab = (row["Tab"])
sep = int((row["Separated"]))

This code gets this error:

File "/usr/local/Cellar/python/2.7.5/Frameworks/Python.framework/Versions/2.7/lib/python2.7/", line 104, in next
row =

I tried to print the rows, to see where I was in the file, and I changed the "range(14)" to range 5, but when I print the row, I get this:

{'Review performed by:': 'Tab/tSeparated/tHeader/tNames/tThat/tI/tWant/tTo/tUse'}
Traceback (most recent call last):
File "", line 396, in <module>
File "", line 234, in main
tab = (row["Tab"])
KeyError: 'Tab'

So I am not really sure the right way to skip those top lines. Any help would be appreciated.

Answer Source

A csv.DictReader reads the first line from the file when it's instantiated, to get the headers for subsequent rows. Therefore it uses Review performed by: as the header row, then you skip the next 14 rows.

Instead, skip the rows before creating the DictReader:

for i in range(14):
reader = csv.DictReader(CSVFile)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download