In this article, I'll show you how to read CSV files without a header in Python. Sometimes, CSV files don't have a header row, and we need to handle that differently. Using Python’s csv
module, we can read these files line by line and process the data easily. Let’s walk through how to do this step by step.
When a CSV file doesn't have a header, we need to manage the data manually, like assigning column names ourselves. Python's csv
module offers ways to handle such cases efficiently. By the end of this article, you'll know how to read and work with CSV files that don’t have a header row.
Python Read CSV File Without Header
Python Read CSV File without Header
main.py
from csv import reader
# skip first line from demo.csv
with open('demo.csv', 'r') as readObj:
csvReader = reader(readObj)
header = next(csvReader)
# Check file as empty
if header != None:
# Iterate over each row after the header in the csv
for row in csvReader:
# row variable is a list that represents a row in csv
print(row)
This method is more structured since it directly maps each row to a dictionary with the header as keys (if it exists), and if you want to skip the header, you just ignore fieldnames
.
import csv
# Open the CSV file
with open('file_with_or_without_header.csv', mode='r') as file:
# Create a DictReader to read the CSV
csv_reader = csv.DictReader(file)
# Check if a header exists and skip it
if csv_reader.fieldnames:
print(f"Header skipped: {csv_reader.fieldnames}")
# Iterate through the rows
for row in csv_reader:
print(row)
In this example:
DictReader
automatically detects the header and uses it as a dictionary key.fieldnames
the property contains the header. If it exists, we skip it.
You might also like:
In this tutorial I will give you example of how to create zip file in laravel 7/8. Some times client's have requirme...
Dec-17-2021
As we know Laravel 9 was officially released yesterday with many new functionalities like Symfony 6.0 components, Symfon...
Feb-10-2022
In this article, we will see Queen Elizabeth II portrait using CSS. Elizabeth II was Queen of the United Kingd...
Sep-11-2022
In this article, we will see a jquery image magnifier on mouse hover. Using an image magnifier you can enlarge...
Jan-04-2021