Working with CSV Files in Python (The csv Module)

3D isometric illustration of a machine organizing text blocks separated by commas into a table, representing Python's CSV module.

While Pandas is great for big data analysis, sometimes you just need to read a simple CSV file. For this, the Python csv module is perfect—it’s fast, light, and requires no installation.

1. Reading a CSV File

This is the most common task. We use csv.reader to loop through the file row by row.

import csv

with open('data.csv', 'r') as file:
    csv_reader = csv.reader(file)
    
    # Skip the header row
    next(csv_reader)
    
    for row in csv_reader:
        # Each 'row' is a list of strings
        print(f"Name: {row[0]}, Age: {row[1]}")

2. Reading a CSV as a Dictionary

This is even better. csv.DictReader uses the header row to create a dictionary for each line.

import csv

with open('data.csv', 'r') as file:
    csv_reader = csv.DictReader(file)
    
    for row in csv_reader:
        # Now you can use column names!
        print(f"Name: {row['Name']}, Age: {row['Age']}")

3. Writing to a CSV File

import csv

# Data to write
header = ['Name', 'Score']
data = [
    ['Alice', 95],
    ['Bob', 80]
]

with open('scores.csv', 'w', newline='') as file:
    csv_writer = csv.writer(file)
    
    csv_writer.writerow(header) # Write a single header row
    csv_writer.writerows(data)  # Write all data rows

Note: The newline='' is a required step to prevent extra blank lines on Windows.

Similar Posts

Leave a Reply