Python csv Module

The csv module in Python provides functionality to read from and write to CSV (Comma-Separated Values) files. CSV files are commonly used for exchanging data between different applications. This module is part of the standard library, so no installation is required.

Table of Contents

  1. Introduction
  2. Key Classes and Functions
    • reader
    • writer
    • DictReader
    • DictWriter
  3. Examples
    • Reading a CSV File
    • Writing to a CSV File
    • Reading a CSV File into a Dictionary
    • Writing a Dictionary to a CSV File
  4. Real-World Use Case
  5. Conclusion
  6. References

Introduction

The csv module provides tools for reading and writing CSV files. It supports various delimiters and quoting options, making it flexible for handling different CSV formats.

Key Classes and Functions

reader

The reader class reads from a CSV file and returns each row as a list.

import csv

with open('example.csv', newline='') as csvfile:
    csvreader = csv.reader(csvfile)
    for row in csvreader:
        print(row)

writer

The writer class writes data to a CSV file.

import csv

with open('example.csv', 'w', newline='') as csvfile:
    csvwriter = csv.writer(csvfile)
    csvwriter.writerow(['Name', 'Age', 'City'])
    csvwriter.writerow(['Alice', '30', 'New York'])

DictReader

The DictReader class reads from a CSV file and returns each row as a dictionary.

import csv

with open('example.csv', newline='') as csvfile:
    csvreader = csv.DictReader(csvfile)
    for row in csvreader:
        print(row)

DictWriter

The DictWriter class writes data to a CSV file from a dictionary.

import csv

with open('example.csv', 'w', newline='') as csvfile:
    fieldnames = ['Name', 'Age', 'City']
    csvwriter = csv.DictWriter(csvfile, fieldnames=fieldnames)
    
    csvwriter.writeheader()
    csvwriter.writerow({'Name': 'Alice', 'Age': '30', 'City': 'New York'})

Examples

Reading a CSV File

import csv

with open('example.csv', newline='') as csvfile:
    csvreader = csv.reader(csvfile)
    for row in csvreader:
        print(row)

Writing to a CSV File

import csv

data = [
    ['Name', 'Age', 'City'],
    ['Alice', '30', 'New York'],
    ['Bob', '25', 'Los Angeles']
]

with open('example.csv', 'w', newline='') as csvfile:
    csvwriter = csv.writer(csvfile)
    csvwriter.writerows(data)

Reading a CSV File into a Dictionary

import csv

with open('example.csv', newline='') as csvfile:
    csvreader = csv.DictReader(csvfile)
    for row in csvreader:
        print(row)

Writing a Dictionary to a CSV File

import csv

data = [
    {'Name': 'Alice', 'Age': '30', 'City': 'New York'},
    {'Name': 'Bob', 'Age': '25', 'City': 'Los Angeles'}
]

with open('example.csv', 'w', newline='') as csvfile:
    fieldnames = ['Name', 'Age', 'City']
    csvwriter = csv.DictWriter(csvfile, fieldnames=fieldnames)
    
    csvwriter.writeheader()
    csvwriter.writerows(data)

Real-World Use Case

Processing a CSV File

Suppose you have a CSV file containing customer data, and you want to filter out customers from a specific city and save the result to a new CSV file.

import csv

def filter_customers(input_file, output_file, city):
    with open(input_file, newline='') as csvfile:
        csvreader = csv.DictReader(csvfile)
        filtered_data = [row for row in csvreader if row['City'] == city]
    
    with open(output_file, 'w', newline='') as csvfile:
        fieldnames = ['Name', 'Age', 'City']
        csvwriter = csv.DictWriter(csvfile, fieldnames=fieldnames)
        
        csvwriter.writeheader()
        csvwriter.writerows(filtered_data)

# Example usage
filter_customers('customers.csv', 'filtered_customers.csv', 'New York')

Conclusion

The csv module in Python provides an easy and flexible way to handle CSV files. Whether you need to read, write, or process CSV data, the csv module offers the necessary tools to perform these tasks efficiently.

References

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top