fbpx

Reading a CSV file in Python

To read a CSV (Comma-Separated Values) file in Python, you can use the csv module from the standard library. The csv module provides functionality to both read from and write to CSV files. Here’s a basic example of reading a CSV file:

Example CSV File (data.csv):

Name, Age, City
John, 25, New York
Alice, 30, London
Bob, 22, Paris

Python Code:

import csv

# Specify the path to your CSV file
csv_file_path = 'path/to/your/file/data.csv'

# Open the CSV file in read mode
with open(csv_file_path, 'r') as file:
    # Create a CSV reader object
    csv_reader = csv.reader(file)

    # Iterate over each row in the CSV file
    for row in csv_reader:
        # Each row is a list of values
        name, age, city = row
        print(f"Name: {name}, Age: {age}, City: {city}")

In this example:

  1. We use the open function to open the CSV file in read mode ('r').
  2. We create a csv.reader object by passing the file object to it.
  3. We iterate over the rows using a for loop, and each row is a list containing the values of the columns.
  4. We unpack the values from each row and print them.

Using csv.DictReader for Dictionary-Based Access:

If your CSV file has headers, and you want to access the data using column names, you can use csv.DictReader. This class returns each row as a dictionary where keys are column names.

import csv

# Specify the path to your CSV file
csv_file_path = 'path/to/your/file/data.csv'

# Open the CSV file in read mode
with open(csv_file_path, 'r') as file:
    # Create a CSV DictReader object
    csv_reader = csv.DictReader(file)

    # Iterate over each row in the CSV file
    for row in csv_reader:
        # Each row is a dictionary
        name = row['Name']
        age = row['Age']
        city = row['City']
        print(f"Name: {name}, Age: {age}, City: {city}")

Using csv.DictReader simplifies data access, especially when dealing with CSV files that have headers.

Make sure to replace 'path/to/your/file/data.csv' with the actual path to your CSV file. Additionally, handle exceptions appropriately, such as FileNotFoundError if the file doesn’t exist or PermissionError if there are permission issues when trying to read the file.