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
Laravel 8 Datatables Filter with Dropdown
Laravel 8 Datatables Filter wi...

In this example we will see laravel 8 datatables filter with dropdown, Here we will add datatables custom...

Read More

Jun-16-2021

Laravel 11 Vite Install Sweetalert2 Example
Laravel 11 Vite Install Sweeta...

Hello, laravel web developers! In this article, we'll see how to install sweetalert2 in laravel 11 vite. Sweeta...

Read More

Jul-15-2024

Angular 13 Crop Image Before Upload With Preview
Angular 13 Crop Image Before U...

In this article, we will see the angular 13 crop image before uploading with a preview. we will give you a sim...

Read More

May-10-2022

How To Use Sweetalert2 In Laravel
How To Use Sweetalert2 In Lara...

Today we will learn how to use sweetalert2 In laravel, You can use sweetalert2 in laravel as well as php, ...

Read More

May-03-2021