bluethundr
bluethundr

Reputation: 1325

Can't skip header row in csv file with python

I'm using the CSV module in python to read a CSV into memory and I need to skip the header row.

I am using the next command to skip the headers, but it isn't working.

import csv
with open(aws_env_list) as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    next(csv_reader)

The headers are still being produced, crashing my script. My script produces the following line:

Working in AWS Account:  companyAccountName,AWSAccountName,Description,LOB,AWSAccountNumber,CIDRBlock,ConnectedtoMontvale,PeninsulaorIsland,URL,Owner,EngagementCode,CloudOpsAccessType

In the original CSV the headers are only on the first line.

The first few lines of my csv file look like this.

What's wrong with the above and why is this not skipping the headers? Is there a better way?

Upvotes: 1

Views: 2299

Answers (1)

ctyler9
ctyler9

Reputation: 88

I don't think you are using the next() function correctly.

Here's the an example from the documentation:

import csv

with open('eggs.csv', newline='') as csvfile:
    spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
    for row in spamreader:
        print(', '.join(row))

When you use csv.reader, it takes the csv file and for each row creates an iterable object. So, if you want to skip the first row (the header row) simply make this change.

with open(aws_env_list) as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    for row in list(csv_reader)[1:]:
        """ do whatever action """

When you add [1:] to the end of csv_reader, it tells it to select only the 2nd object (since 0 is the first). You create in essence a subset of the object which does not contain the first element.

Upvotes: 3

Related Questions