Python Program To Delete a Row in CSV File

 

Method-1

You can delete a row in a CSV file in Python by reading the CSV file, excluding the row you want to delete, and then writing the remaining data back to the file. Here’s a Python program to do that:

 

import csv

# Specify the CSV file and the row index you want to delete
csv_file = 'example.csv'
row_index_to_delete = 2  # Replace with the index of the row you want to delete (0-based)

# Read the CSV file and exclude the row to delete
data = []
with open(csv_file, 'r', newline='') as file:
    csv_reader = csv.reader(file)
    for index, row in enumerate(csv_reader):
        if index != row_index_to_delete:
            data.append(row)

# Write the remaining data back to the CSV file
with open(csv_file, 'w', newline='') as file:
    csv_writer = csv.writer(file)
    csv_writer.writerows(data)

print(f"Row {row_index_to_delete} deleted from {csv_file}")

 

Make sure to replace 'example.csv' with the path to your CSV file and set row_index_to_delete to the index of the row you want to delete (0-based index). This code will read the CSV file, exclude the specified row, and then overwrite the file with the updated data, effectively deleting the row.

Method-2

You can also use a different method to delete a row in a CSV file in Python using the pandas library, which can simplify the process. Here’s an example of how to do it with pandas:

First, you’ll need to install the pandas library if you haven’t already. You can install it using pip:


pip install pandas

 

Now, you can use pandas to delete a row from a CSV file:

import pandas as pd

# Specify the CSV file and the row index you want to delete
csv_file = 'example.csv'
row_index_to_delete = 2  # Replace with the index of the row you want to delete (0-based)

# Read the CSV file into a DataFrame
df = pd.read_csv(csv_file)

# Delete the specified row
df = df.drop(row_index_to_delete)

# Write the DataFrame back to the CSV file without the deleted row
df.to_csv(csv_file, index=False)

print(f"Row {row_index_to_delete} deleted from {csv_file}")

 

This code uses the pandas library to read the CSV file into a DataFrame, delete the specified row, and then write the DataFrame back to the same CSV file without the deleted row. Replace 'example.csv' with the path to your CSV file and set row_index_to_delete to the index of the row you want to delete (0-based index).

 

Method-3

There are multiple methods to delete a row from a CSV file in Python. In addition to the previously mentioned methods, here are a couple of alternative approaches:

Using csv.DictReader and csv.DictWriter:

 

import csv

# Specify the CSV file and the row index you want to delete
csv_file = 'example.csv'
row_index_to_delete = 2  # Replace with the index of the row you want to delete (0-based)

# Read the CSV file and write the data excluding the specified row
with open(csv_file, 'r', newline='') as infile, open('temp.csv', 'w', newline='') as outfile:
    reader = csv.DictReader(infile)
    fieldnames = reader.fieldnames
    writer = csv.DictWriter(outfile, fieldnames=fieldnames)
    writer.writeheader()

    for index, row in enumerate(reader):
        if index != row_index_to_delete:
            writer.writerow(row)

import os
os.replace('temp.csv', csv_file)
print(f"Row {row_index_to_delete} deleted from {csv_file}")

This code reads the CSV file using csv.DictReader, excludes the specified row, and then writes the data back to a temporary file. Finally, it replaces the original CSV file with the temporary file.

Method-4

Using the open() function and csv.writer:

 

import csv

# Specify the CSV file and the row index you want to delete
csv_file = 'example.csv'
row_index_to_delete = 2  # Replace with the index of the row you want to delete (0-based)

# Read the CSV file and write the data excluding the specified row
with open(csv_file, 'r', newline='') as infile, open('temp.csv', 'w', newline='') as outfile:
    reader = csv.reader(infile)
    writer = csv.writer(outfile)
    for index, row in enumerate(reader):
        if index != row_index_to_delete:
            writer.writerow(row)

import os
os.replace('temp.csv', csv_file)
print(f"Row {row_index_to_delete} deleted from {csv_file}")

 

This code uses the open() function to read and write the CSV file row by row, excluding the specified row, and then replaces the original CSV file with the temporary file.

By cbsepython

A complete solution for the students of class 9 to 12 having subject Information Technology (402), Computer Science (083). Explore our website for all the useful content as Topic wise notes, Solved QNA, MCQs, Projects and Quiz related to the latest syllabus.

Copywrite © 2020-2024, CBSE Python,
All Rights Reserved