Back to Blog
Lesson 20 of the Python: Programming from Zero with Python course
PythonAugust 6, 20263 min read

Working with CSV Files: A Practical Guide for Python Beginners

Master the Python csv module to read and write structured data. Learn to handle CSV files efficiently for your data-processing projects and CLI tools.

PythonCSVdata storagemodulefile I/O
Neatly arranged blue office binders labeled with dates and names for organized storage.

Previously in this course, we covered Writing to Files: A Practical Guide to Data Persistence in Python, where we learned how to use context managers to save raw text. Today, we’re leveling up: instead of just writing raw strings, we will handle structured data using the CSV (Comma-Separated Values) format.

Why CSV?

A CSV file is essentially a plain-text table where each line represents a row, and each field is separated by a comma. It’s the "universal language" of data exchange because it’s simple, lightweight, and supported by every spreadsheet application and database on earth.

The csv Module

Python includes a built-in csv module that handles the messy parts of CSV parsing—like dealing with commas inside strings or special line-ending characters. You don't need to manually split strings or worry about edge cases; the module does the heavy lifting for you.

Reading CSV Files

When reading, the csv.reader object acts as an iterator. Each time you loop through it, you get a list of strings representing the columns in that row.

PYTHON
import csv

# Assuming CE9178">'data.csv' looks like:
# Name,Age,Role
# Alice,30,Developer
# Bob,25,Designer

with open(CE9178">'data.csv', mode=CE9178">'r') as file:
    reader = csv.reader(file)
    # Skip the header row if it exists
    next(reader) 
    
    for row in reader:
        # row is a list: [CE9178">'Alice', CE9178">'30', CE9178">'Developer']
        name, age, role = row
        print(f"{name} is a {role} who is {age} years old.")

Writing CSV Files

Writing is just as straightforward. We use csv.writer and its writerow() method. Note that you must open the file with newline='' to ensure cross-platform compatibility, preventing extra empty rows on Windows.

PYTHON
import csv

data = [
    [CE9178">'Name', CE9178">'Age', CE9178">'Role'],
    [CE9178">'Charlie', CE9178">'28', CE9178">'Manager'],
    [CE9178">'Dana', CE9178">'32', CE9178">'Analyst']
]

with open(CE9178">'output.csv', mode=CE9178">'w', newline=CE9178">'') as file:
    writer = csv.writer(file)
    writer.writerows(data) # Writes the entire list of lists at once

Advancing Our Project

In our running project, we've been collecting data in memory. Now, we can persist that data. Let's update our logic to save our collected statistics to a file so that when we restart the program, our data isn't lost.

PYTHON
def save_data(filename, data_list):
    with open(filename, mode=CE9178">'w', newline=CE9178">'') as file:
        writer = csv.writer(file)
        # Write headers
        writer.writerow([CE9178">'Name', CE9178">'Value'])
        # Write individual entries
        for entry in data_list:
            writer.writerow([entry[CE9178">'name'], entry[CE9178">'value']])

Practice Exercise

Create a script that:

  1. Creates a file named inventory.csv.
  2. Writes three rows of data: Item, Quantity, and Price.
  3. Re-opens the file, reads the data, and calculates the total value (Quantity * Price) for each item, printing the result to the console.

Common Pitfalls

  • The Missing newline='': If you omit newline='' when opening a file for writing, you might find blank rows between your data entries on certain operating systems.
  • Assuming Data Types: Everything read from a CSV is a string. If your CSV contains 25 (age), it comes into Python as '25'. You must manually cast it using int() or float() if you intend to perform arithmetic.
  • Header Confusion: Always remember whether your file has a header. If you call next(reader) when there is no header, you will skip your first row of actual data.

FAQ

Q: Can I use a delimiter other than a comma? A: Yes! You can change the delimiter in csv.reader or csv.writer by adding the argument delimiter=';' or delimiter='\t' (for tab-separated files).

Q: Is the CSV format suitable for complex, nested data? A: No. CSV is flat by nature. If you have nested structures (like a user having multiple addresses), you'll want to use JSON, which we will cover in the next lesson.

Recap

We’ve learned to use the csv module to serialize and deserialize structured data. By using reader and writer objects, we can move beyond raw file I/O into data persistence that other programs can easily consume.

Up next: Working with JSON

Similar Posts