Nono.MA

Read CSV files with Python

LAST UPDATED FEBRUARY 3, 2023

Here's how to read contents from a comma-separated value (CSV) file in Python; maybe a CSV that already exists or a CSV you saved from Python.

Read CSV and print rows

import csv

csv_file_path = 'file.csv'

with open(csv_file_path, encoding='utf-8') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')

    # Print the first five rows
    for row in list(csv_reader)[:5]:
        print(row)

    # Print all rows
    for row in list(csv_reader)[:5]:
        print(row)

BlogCodePythonTil