← Back to Python

All Topics

Advertisement

Learn/Python/Advanced Python

CSV Module

Topic: Data Processing

Advertisement

Introduction

The csv module provides functionality for reading and writing CSV files.

Reading CSV

import csv

with open("data.csv", "r") as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)

# With headers
with open("data.csv", "r") as f:
    reader = csv.DictReader(f)
    for row in reader:
        print(row["name"], row["age"])

Writing CSV

with open("output.csv", "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerow(["Name", "Age", "City"])
    writer.writerows([
        ["Alice", 30, "NYC"],
        ["Bob", 25, "LA"]
    ])

# With dictionaries
with open("output.csv", "w", newline="") as f:
    writer = csv.DictWriter(f, fieldnames=["name", "age"])
    writer.writeheader()
    writer.writerow({"name": "Alice", "age": 30})

Custom Delimiters

# Tab-separated
writer = csv.writer(f, delimiter="\t")

# Custom quoting
writer = csv.writer(f, quoting=csv.QUOTE_ALL)

Practice Problems

  1. Read CSV with different delimiters
  2. Convert CSV to dictionary
  3. Handle missing values in CSV
  4. Write nested data to CSV
  5. Merge multiple CSV files

Advertisement

Advertisement

Need More Practice?

Get personalized Python help from ChatWhole's AI-powered platform.

Get Expert Help →