Categories
Python Answers

How to ignore the first line of data when processing CSV data with Python?

Spread the love

Sometimes, we want to ignore the first line of data when processing CSV data with Python.

In this article, we’ll look at how to ignore the first line of data when processing CSV data with Python.

How to ignore the first line of data when processing CSV data with Python?

To ignore the first line of data when processing CSV data with Python, we can call next to skip to the next row.

For instance, if we have:

test.csv

col1,col2
1,2
3,4
5,6

Then we write:

import csv
with open('test.csv') as f:
    f_csv = csv.reader(f)
    headers = next(f_csv)
    for row in f_csv:
        print(row)

to open the test.csv with open.

Then we call csv.reader with f to read the file.

Next, we skip the first row by calling next with f_csv.

The first row’s data is returned with next and assigned to headers.

And finally, we loop through the rest of the rows with a for loop and print each row.

Therefore, we see:

['1', '2']
['3', '4']
['5', '6']

printed.

Conclusion

To ignore the first line of data when processing CSV data with Python, we can call next to skip to the next row.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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