Python Read CSV File Without Header

Websolutionstuff | Sep-20-2024 | Categories : Python

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

 

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.
  • The fieldnames the property contains the header. If it exists, we skip it.
  • The remaining rows are read as dictionaries, which you can process accordingly.

 


You might also like:

Recommended Post
Featured Post
How To Create Zip File In Laravel 7/8
How To Create Zip File In Lara...

In this tutorial I will give you example of how to create zip file in laravel 7/8. Some times client's have requirme...

Read More

Dec-17-2021

Laravel 9 CRUD Operation Example
Laravel 9 CRUD Operation Examp...

As we know Laravel 9 was officially released yesterday with many new functionalities like Symfony 6.0 components, Symfon...

Read More

Feb-10-2022

Queen Elizabeth II Portrait Using CSS
Queen Elizabeth II Portrait Us...

In this article, we will see Queen Elizabeth II portrait using CSS. Elizabeth II was Queen of the United Kingd...

Read More

Sep-11-2022

jQuery Image Magnifier on Mouse Hover
jQuery Image Magnifier on Mous...

In this article, we will see a jquery image magnifier on mouse hover. Using an image magnifier you can enlarge...

Read More

Jan-04-2021