Recent chats
ASKGEEZ Q&A GUIDETechnology & devices

How can I read a CSV file with Python’s csv module?

Quick answer

Import csv, open the file in read mode with newline='' and an explicit encoding such as utf-8, then pass it to csv.reader. Each parsed row is returned as a list. If the first row contains column names, consume it with next(reader) before looping over the remaining rows. The example reads and prints values; it does not write to the input file. [S1]

LET’S WORK THROUGH IT

The question, the details, the next step.

Question

I have a small CSV file with a header row. What’s the simplest way to read it and print each row in Python without changing the file?

Geez

Use the standard-library csv module. Assume the file is named people.csv and contains comma-separated data with a header row:

name,city
Ari,Accra
Sam,Lagos

Here is a complete Python example:

import csv

with open("people.csv", "r", newline="", encoding="utf-8") as csv_file:
    reader = csv.reader(csv_file)
    header = next(reader)
    print("Header:", header)

    for row in reader:
        print(row)

The documented pattern is to open the file with newline=''; specifying encoding='utf-8' requests UTF-8 text decoding. csv.reader returns each parsed row as a list, so this example consumes the first list as the header and prints each later list. [S1]

For the sample data, the output is:

Header: ['name', 'city']
['Ari', 'Accra']
['Sam', 'Lagos']

This output is illustrative, based on the assumed sample file. The code opens the file in read mode ("r") and only prints values; it contains no file-writing operation.

Follow-up question

Why are newline='' and encoding='utf-8' included? Can I leave them out?

Geez

newline='' lets the CSV module handle newline conventions, including newlines inside quoted fields. The Python documentation recommends this when opening a CSV file for reading. encoding='utf-8' explicitly requests UTF-8 text decoding. [S1]

You can omit either setting, but then you are not using those documented settings. This example assumes the file is UTF-8; if it uses another encoding, UTF-8 may not decode it as intended. The documentation shows how to request UTF-8; it does not establish the encoding of your particular file.

Follow-up question

How do I print the rows but not the header? And what if the file might be empty?

Geez

For a file with a header, next(reader) consumes its first row, so the loop starts with the data rows. To handle an empty file without StopIteration, give next() a default value:

import csv

with open("people.csv", "r", newline="", encoding="utf-8") as csv_file:
    reader = csv.reader(csv_file)
    header = next(reader, None)

    if header is None:
        print("The file is empty.")
    else:
        for row in reader:
            print(row)

This empty-file check does not establish whether a nonempty file has column names. If the file has no header, do not skip its first row; use the format you expect for that file.

Follow-up question

What should I check if the printed rows don’t look like the columns in my spreadsheet?

Geez

Check the file-format assumptions first. The example expects ordinary comma-separated data and a header in the first row. CSV dialects can differ among applications, so not every file necessarily uses commas or the same conventions. [S1] Inspect a small excerpt as text and confirm the delimiter and whether the first row is a header before changing the reader. The example cannot establish the format or encoding of your particular file.

As a starting checklist: choose the correct filename, open it in read mode with newline='' and the expected encoding, create a reader, and decide whether to consume the first row as a header. Keep reading inside the with block. The example prints parsed values; it does not preserve spreadsheet formatting or modify the input file.

A practical checklist

  • Replace people.csv with the path to your input file.

  • Use the encoding your file is expected to have; the example requests UTF-8.

  • Open the file in read mode with newline=''.

  • Use csv.reader(csv_file) and decide whether to consume the first row as a header.

  • Print rows inside the with block; avoid write operations if you only want to read.

A few more useful answers

Does `csv.reader` return dictionaries keyed by the header names?

No. csv.reader returns each parsed row as a list. This example prints the header and rows separately; it does not map values to column names. [S1]

Will this example work with every spreadsheet export?

Not necessarily. It assumes ordinary comma-separated data, while CSV dialects can differ among applications. Check the file’s actual format if the rows do not split as expected. [S1]

Does printing rows change the CSV file?

No. The example opens the file in read mode and prints values; it does not write to the input file.

Sources

References used for this guide.

  1. [S1] csv — CSV file reading and writing
    docs.python.org · Checked

YOUR QUESTION. YOUR DETAILS.

Let’s work through your situation.

Get a tailored answer or help with your next task. Starts at $1, with a quote before you pay.

Ask your own question
← Back to Geez at Work