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 example we will see laravel 8 datatables filter with dropdown, Here we will add datatables custom...
Jun-16-2021
Hello, laravel web developers! In this article, we'll see how to install sweetalert2 in laravel 11 vite. Sweeta...
Jul-15-2024
In this article, we will see the angular 13 crop image before uploading with a preview. we will give you a sim...
May-10-2022
Today we will learn how to use sweetalert2 In laravel, You can use sweetalert2 in laravel as well as php, ...
May-03-2021