Retrieve A Specific Element In a Csv File using Python

We have given a file and our task is to retrieve a specific element in a CSV file using Python. In this article, we will see some generally used methods for retrieving a specific element in a CSV file.

Retrieve a Specific Element in a CSV File Using Python

Below are some of the ways by which we can retrieve a specific element in a CSV file using Python:

  • Using CSV Module
  • Using the Pandas Library

data.csv

"Course","Description"
"HTML","Hypertext Markup Language"
"CSS","Cascading Style Sheets"
"ReactJS","JavaScript library for building user interfaces"
"Python","High-level programming language"

Using CSV Module

In this example, we are using the csv module in Python to open and read a CSV file named ‘data.csv‘. We skip the header row using next(reader, None) and then loop through each row in the CSV file. We check if the first column of each row matches ‘ReactJS‘ and if it does, we print the corresponding description of ReactJS from the second column.

Python
import csv

with open('data.csv', newline='') as csvfile:
    reader = csv.reader(csvfile)
    next(reader, None)
    for row in reader:
        if row[0] == 'ReactJS':
            print(f"Description of ReactJS: {row[1]}")

Output:

Description of ReactJS: JavaScript library for building user interfaces

Using the Pandas library

In this method, the CSV file is read into a DataFrame using the pandas package. The DataFrame is then filtered to identify the row where the course name that has been entered in the ‘Course‘ column matches. As soon as the row is obtained, we take the description out of the ‘Description‘ column and provide it back.

Python
import pandas as pd

def retrieve_description(course_name, filename):
    df = pd.read_csv(filename)
    description = df.loc[df['Course'] == course_name, 'Description'].values[0]
    return description

filename = 'data.csv'
course_name = 'ReactJS'
description = retrieve_description(course_name, filename)
print(f"Description of {course_name}: {description}")

Output:

Description of ReactJS: JavaScript library for building user interfaces

Conclusion

In conclusion, retrieving a specific element from a CSV file in Python can be accomplished using either the csv module or the pandas library. Both methods offer efficient ways to access and extract data based on criteria such as column values or row indices. These approaches provide flexibility and scalability for working with CSV files in Python.


Contact Us