Python CSV: Reading and Writing Spreadsheets

Learn how to handle CSV data in Python. Master csv.reader, csv.writer, and DictReader/DictWriter for efficient table parsing.

Try Python CSV Code

Overview

CSV (Comma-Separated Values) is a ubiquitous format for exporting and importing data from spreadsheets and relational databases. Because CSV files are simple text files, they are universally supported by analytical tools, database platforms, and programming languages. Python features a built-in `csv` module specifically optimized for parsing, writing, and manipulating tabular data without needing third-party libraries like pandas.

The csv module provides two primary interfaces: list-based readers/writers and dictionary-based readers/writers. `csv.reader()` and `csv.writer()` represent each line in the CSV as a list of strings, which is simple but requires referencing columns by their numerical index. For a more robust approach, developers use `csv.DictReader()` and `csv.DictWriter()`. These classes map each row to a dictionary using the CSV header row as keys, producing highly readable code that doesn't break if columns are reordered.

When dealing with CSV files, syntax details matter. Different programs use different delimiters (like tabs or semicolons) and handle quotes or line endings in distinct ways. The `csv` module allows you to define custom delimiters, quoting rules, and escape characters via a 'dialect' parameter. Additionally, when opening CSV files in Python, it is a critical requirement to pass `newline=''` to the `open()` function to prevent blank line issues across different operating systems.

Code Example

Writing data to a CSV file using DictWriter and reading it back with DictReader.

csv_demo.py
Try in Editor
import csv

filename = "employees.csv"
fieldnames = ["id", "name", "department"]
data = [
    {"id": "101", "name": "Bob", "department": "HR"},
    {"id": "102", "name": "Alice", "department": "Engineering"}
]

# Write dict data to CSV
with open(filename, "w", newline="") as csvfile:
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()
    writer.writerows(data)

print("CSV written successfully.\n--- Reading CSV ---")

# Read CSV data back as dictionaries
with open(filename, "r", newline="") as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        print(f"Employee {row['name']} works in {row['department']}.")
Terminal Output
CSV written successfully.
--- Reading CSV ---
Employee Bob works in HR.
Employee Alice works in Engineering.

Real-world Use Cases

  • Exporting spreadsheet records for financial analysis
  • Importing contact list catalogs into databases
  • Formatting statistical outputs from computational scripts

Frequently Asked Questions

Why do I need to specify newline="" when opening a CSV file?

This is required by the csv module's internal writer to prevent extra blank lines from being inserted, particularly on Windows platforms.

How can I parse a CSV file that uses tabs instead of commas?

You can pass the delimiter parameter to the reader or writer, e.g., csv.reader(file, delimiter='\t').

Keep Learning

Recommended Python Resources

Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.