Course contentsShow
← Python
Lesson 734 of 1,06011. Standard Library EssentialsFree lesson

Reading and Writing Tabular Data with CSV

Utilize the built-in CSV module to handle structured spreadsheet data, ensuring proper delimiter management and row-based data processing.

In this lesson, you will learn how to leverage Python’s built-in csv module to programmatically read from and write to structured, row-based tabular files.

While you could treat a CSV file like any other text file using standard file operations, the csv module simplifies the process by automatically handling complex delimiters, quoting, and row parsing. This ensures your data remains structured, even if it contains characters like commas or line breaks within individual cells.

Writing Tabular Data

To write data, you use csv.writer. This creates an object that converts Python lists into properly formatted strings.

import csv

data = [
    ["Name", "Department", "ID"],
    ["Alice", "Engineering", 101],
    ["Bob", "Marketing", 102]
]

with open('employees.csv', 'w', newline='') as file:
    writer = csv.writer(file)
    writer.writerows(data)

The newline='' argument is crucial when working with the csv module; it prevents the underlying system from inserting extra blank lines between rows on different operating systems.

Reading Tabular Data

To read data, you use csv.reader. This provides an iterator that yields each row as a list of strings, effectively mapping the file structure into a sequence of Python objects.

with open('employees.csv', 'r') as file:
    reader = csv.reader(file)
    # Skip the header row if necessary
    header = next(reader)
    for row in reader:
        print(f"Processing: {row[0]} from {row[1]}")

Managing Delimiters

Not every "CSV" file uses a comma. Sometimes you will encounter files separated by tabs (TSV) or semicolons. You can handle these seamlessly by providing the delimiter argument to the reader or writer:

# For tab-separated files
reader = csv.reader(file, delimiter='\t')

By abstracting the nuances of character escaping and row termination, the csv module allows you to focus on the content of your data rather than the mechanics of file parsing.

Key Takeaway: The csv module provides a robust, standardized interface to handle tabular data, ensuring that row-based parsing and delimiter management remain consistent across your applications.