next(reader) deleting the first row of data

Viewed 22

I'm writing a python script that reads a csv file and iterates through for any cells with an inequality and adds a new column and splits the inequality to the new cell. I want to ignore the first row of the csv as its the header but usinig next(reader) also removes the first row of data.

    reader = csv.DictReader(inFile)
    first_row = next(reader)
    fieldnames = list(reader.fieldnames)
    for key, value in first_row.items():
        if any(value.startswith(char) for char in ['<', '=', '>']):
            fieldnames.append(key+'_inequality')
1 Answers

When you use a csv.DictReader without a fieldnames argument it consumes the first row of the csv to get the dictionary keys. This means that the header is already gone. The result is that next(reader) consumes your first row of data. Getting rid of first_row = next(reader) will solve your problem.

Note: If you were using a csv.DictReader with a fieldnames argument or a csv.reader the first row would contain the headings (if they were present in the file) and it would make sense to do first_row = next(reader).

Heres the relevant portion from the docs for csv.DictReader:

The fieldnames parameter is a sequence. If fieldnames is omitted, the values in the first row of file f will be used as the fieldnames. Regardless of how the fieldnames are determined, the dictionary preserves their original ordering.

Related