How to Read a CSV File in Python | The School of Code

Settings

Appearance

Choose a typography theme that suits your style

Back to How-to Guides
Python

How to Read a CSV File in Python

Learn how to read CSV files in Python using pandas and the built-in csv module.

PythonCSVpandasData Import

Reading CSV files is one of the most common data import tasks in Python. Here are the main methods to accomplish this.

The easiest way to read a CSV file is with pandas:

import pandas as pd

# Read a CSV file
df = pd.read_csv('data.csv')

# View the first few rows
print(df.head())

Common Options

# Specify a different delimiter
df = pd.read_csv('data.csv', sep=';')

# Skip header rows
df = pd.read_csv('data.csv', skiprows=2)

# Use specific columns
df = pd.read_csv('data.csv', usecols=['name', 'age'])

# Handle missing values
df = pd.read_csv('data.csv', na_values=['NA', 'N/A', ''])

Method 2: Using the csv Module

For simpler needs, use Python’s built-in csv module:

import csv

with open('data.csv', 'r') as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)

Reading as Dictionaries

import csv

with open('data.csv', 'r') as file:
    reader = csv.DictReader(file)
    for row in reader:
        print(row['name'], row['age'])

Summary

  • Use pandas.read_csv() for data analysis workflows
  • Use the csv module for simple file processing
  • Both methods handle large files efficiently