Skip the headers when editing a csv file using Python

Skip the headers when editing a csv file using Python

Your reader variable is an iterable, by looping over it you retrieve the rows.

To make it skip one item before your loop, simply call next(reader, None) and ignore the return value.

You can also simplify your code a little; use the opened files as context managers to have them closed automatically:

with open(tmob_notcleaned.csv, rb) as infile, open(tmob_cleaned.csv, wb) as outfile:
   reader = csv.reader(infile)
   next(reader, None)  # skip the headers
   writer = csv.writer(outfile)
   for row in reader:
       # process each row

# no need to close, the files are closed automatically when you get to this point.

If you wanted to write the header to the output file unprocessed, thats easy too, pass the output of next() to writer.writerow():

headers = next(reader, None)  # returns the headers or `None` if the input is empty
if headers:

Another way of solving this is to use the DictReader class, which skips the header row and uses it to allowed named indexing.

Given foo.csv as follows:


Use DictReader like this:

import csv
with open(foo.csv) as f:
    reader = csv.DictReader(f, delimiter=,)
    for row in reader:
        print(row[FirstColumn])  # Access by column header instead of column number

Skip the headers when editing a csv file using Python

Doing row=1 wont change anything, because youll just overwrite that with the results of the loop.

You want to do next(reader) to skip one row.

Leave a Reply

Your email address will not be published. Required fields are marked *