Home » Reading a CSV File using the CSV Module in Python

Reading a CSV File using the CSV Module in Python

by maxguy71

In this example we will open a csv file using the csv module

The contents of our test csv file called Countries2.csv was

Entry,Country,Capital
1,France,Paris
2,Germany,Berlin
3,Spain,Madrid
4,Italy,Rome
5,UK,London

Example

We use the open() function to open the csv file, which returns a file object. This is then passed to the reader.

The csv.reader() method returns a reader object which will iterate over each line in the given CSV file.

Each row read from the file is returned as a list of strings.

import csv

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

When you run this you will see something like this

>>> %Run readcsv1.py
['Entry', 'Country', 'Capital']
['1', 'France', 'Paris']
['2', 'Germany', 'Berlin']
['3', 'Spain', 'Madrid']
['4', 'Italy', 'Rome']
['5', 'UK', 'London']

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More