HOWTO · Python

How to Read CSV Line by Line in Python

This article discusses how we can read a CSV file line by line in Python.

On this page

Use Python’s standard-library csv module to process a CSV file one record at a time. csv.reader yields each record as a list, while csv.DictReader uses the header fields as dictionary keys. The examples below create their own sample file, so you can run them as written; replace that setup with your file path when adapting them.

Prepare a CSV file for the examples

A CSV record is a row of fields, often separated by commas. A header is an optional first record that names the fields. CSV files can also contain quoted fields, such as a name with a comma, so use Python’s csv module instead of splitting each line on commas yourself.

You can make a file in a spreadsheet or a plain text editor such as Notepad. For this example, the sample content is Roll Number,Name,Subject followed by 1,Harry Potter,Magical Creatures, 2,Ron Weasley,Divination, and 3,Hermione Granger,Dark arts. Save equivalent content as Demo.csv if you want to follow along with a file on disk.

Read each CSV row with csv.reader

csv.reader is useful when the fields’ positions matter. It yields each record as a list of strings, including the header if one is present. Iterating over the reader processes records incrementally; it does not guarantee that exactly one physical line is resident in memory, since buffering and multiline quoted fields can affect reading.

Run this example:

import csv
import os
import tempfile

rows = [
    ["Roll Number", "Name", "Subject"],
    ["1", "Harry Potter", "Magical Creatures"],
    ["2", "Ron Weasley", "Divination"],
    ["3", "Hermione Granger", "Dark arts"],
]
path = ""
try:
    with tempfile.NamedTemporaryFile("w", newline="", encoding="utf-8", delete=False) as file:
        path = file.name
        csv.writer(file).writerows(rows)
    with open(path, newline="", encoding="utf-8") as file:
        for row in csv.reader(file):
            print(row)
finally:
    if path and os.path.exists(path):
        os.remove(path)
['Roll Number', 'Name', 'Subject']
['1', 'Harry Potter', 'Magical Creatures']
['2', 'Ron Weasley', 'Divination']
['3', 'Hermione Granger', 'Dark arts']

The with statement closes the file when iteration finishes, including if processing stops early. Use newline="" when opening files for the csv module, and specify an encoding such as UTF-8 so text is decoded consistently. The open() mode is "r" by default; use "w" when creating a file as in the sample setup.

Skip the header and handle an empty file

When the first record contains column names, call the built-in next() with a default value to consume it safely. next(reader, None) returns None if there is no first record, so the loop can run only when a header was found. An empty file and a header-only file both produce no data rows.

This runnable example shows both a file with a header and an empty file:

import csv
import os
import tempfile

def data_rows(content):
    path = ""
    try:
        with tempfile.NamedTemporaryFile("w", newline="", encoding="utf-8", delete=False) as file:
            path = file.name
            file.write(content)
        with open(path, newline="", encoding="utf-8") as file:
            reader = csv.reader(file)
            header = next(reader, None)
            return list(reader) if header is not None else []
    finally:
        if path and os.path.exists(path):
            os.remove(path)

print(data_rows("Name,Subject\nHarry Potter,Magical Creatures\n"))
print(data_rows(""))
[['Harry Potter', 'Magical Creatures']]
[]

The optional default matters: calling next(reader) without it has no first value to return for an empty file. If your input does not have a header, do not consume the first row; iterate over the reader directly as in the previous example.

Read rows as dictionaries with csv.DictReader

Choose csv.DictReader when field names are clearer than numeric positions. It treats the first record as the header by default and maps each following record to a dictionary. The values remain strings, so convert a value explicitly when a number is needed.

import csv
import os
import tempfile

content = (
    "Roll Number,Name,Subject\n"
    "1,Harry Potter,Magical Creatures\n"
    "2,Ron Weasley,Divination\n"
    "3,Hermione Granger,Dark arts\n"
)
path = ""
try:
    with tempfile.NamedTemporaryFile("w", newline="", encoding="utf-8", delete=False) as file:
        path = file.name
        file.write(content)
    with open(path, newline="", encoding="utf-8") as file:
        for row in csv.DictReader(file):
            print(row)
finally:
    if path and os.path.exists(path):
        os.remove(path)
{'Roll Number': '1', 'Name': 'Harry Potter', 'Subject': 'Magical Creatures'}
{'Roll Number': '2', 'Name': 'Ron Weasley', 'Subject': 'Divination'}
{'Roll Number': '3', 'Name': 'Hermione Granger', 'Subject': 'Dark arts'}

For example, a row can be accessed with row["Name"]. DictReader uses the header values as keys; if the file has no header, provide field names with the fieldnames argument rather than letting the first data record become the header.

Choose between row lists and dictionaries

Use csv.reader when you want compact lists and know which position contains each field, such as row[0] for the first column. Use csv.DictReader when names such as row["Subject"] make the code easier to understand or maintain. Both readers iterate through records, and both leave fields as strings unless your code converts them. For large files, process each yielded row inside the loop instead of collecting all rows into a list.