Skip to content

Reading & Writing CSV Files

CSV (Comma Separated Values) is a very common format for data science and spreadsheets. Python has a built-in csv module to handle this.

1. Reading CSV

Imagine a file named students.csv:

name,age,city
Vishnu,25,Surat
Ankit,22,Mumbai

Using csv.reader

import csv

with open('students.csv', mode='r') as file:
    csv_reader = csv.reader(file)
    for row in csv_reader:
        print(row) # Each row is a list: ['Vishnu', '25', 'Surat']

2. Writing CSV

To write data to a CSV file, we use csv.writer.

import csv

data = [
    ['Name', 'Score'],
    ['Vishnu', 95],
    ['Ankit', 88]
]

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

3. The Professional Way: csv.DictReader

This allows you to access data by the column headers (keys) instead of index numbers.

with open('students.csv', mode='r') as file:
    reader = csv.DictReader(file)
    for row in reader:
        print(row['name']) # Prints: Vishnu, Ankit

Large Data?

For very large CSV files (millions of rows), professional developers usually use the Pandas library instead of the built-in csv module.

import pandas as pd
df = pd.read_csv('students.csv')