How can I read a CSV file in Python and extract specific columns?

99 views

How can I read a CSV file in Python and extract specific columns?

How can I read a CSV file in Python and extract specific columns?

solveurit24@gmail.com Changed status to publish February 13, 2025
0

Use Python’s csv module to read CSV files. Here’s an example:

import csv

# Read the CSV file
with open('data.csv', 'r') as csvfile:
    reader = csv.DictReader(csvfile)
    # Extract the 'Name' and 'Age' columns
    for row in reader:
        print(f"Name: {row['Name']}, Age: {row['Age']}")

 

Explanation:

  • csv.DictReader reads the CSV file and maps the columns to a dictionary using the header row.
  • You can access any column by its header name (e.g., row['Name']).
solveurit24@gmail.com Changed status to publish February 13, 2025
0