Explain Codes LogoExplain Codes Logo

How to skip the headers when processing a csv file using Python?

python
csv-reader
dataframe
pandas
Alex KataevbyAlex Kataev·Feb 21, 2025
TLDR

Here's how to skip the headers while processing a CSV file in Python:

import csv with open('data.csv') as file: reader = csv.reader(file) next(reader) # Sayonara, headers! for row in reader: print(row) # Now, you see just the data

On-demand header manipulations

Here are some scenarios where you might need to interact with the headers, rather than just skipping them:

Keeping headers handy

Save the headers before taking the leap:

import csv with open('data.csv') as file: reader = csv.reader(file) headers = next(reader) # Super saver, just in case! for row in reader: # Process the rest of the data

Venturing beyond "," delimiter

Not all CSV files stick with commas. If yours uses different delimiters, specify it:

reader = csv.reader(file, delimiter=';') # Semicolons are cool too!

Fencing off headers to another file

Who does not like organization? Put the headers into another file:

import csv with open('data.csv') as infile, open('headers.csv', 'w') as outfile: reader = csv.reader(infile) writer = csv.writer(outfile) writer.writerow(next(reader)) # Headers, packed and moved! for row in reader: # Handle the rest of the data

More ways to dodge headers

Bypassing headers with next() is fail-safe, but there are more methods if you're feeling adventurous!

DictReader for lavish access

Use csv.DictReader for easy access to your CSV rows via headers:

with open('data.csv') as file: reader = csv.DictReader(file) for row in reader: print(row['Header_Name']) # Show some love for headers!

The csv.DictReader skips headers by default.

Skipping headers with a slice of Python

Slice the reader object like bread to jump the header line:

with open('data.csv') as file: rows = list(csv.reader(file))[1:] # Slice to skip the header for row in rows: print(row)

It's efficient but beware! This method loads the entire file into memory.