Skip the headers when editing a csv file using Python Skip the headers when editing a csv file using Python python 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       writer.writerow(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, that's easy too, pass the output of next() to writer.writerow():

headers = next(reader, None)  # returns the headers or `None` if the input is emptyif headers:    writer.writerow(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:

FirstColumn,SecondColumnasdf,1234qwer,5678

Use DictReader like this:

import csvwith 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        print(row['SecondColumn'])


Doing row=1 won't change anything, because you'll just overwrite that with the results of the loop.

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