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

Reading a CSV File using the CSV Module in Python

Java SE 11 Programmer II [1Z0-816] Practice Tests
Oracle Java Certification
1 Year Subscription
Java SE 11 Developer (Upgrade) [1Z0-817]
Java SE 11 Programmer I [1Z0-815] Practice Tests
Spring Framework Basics Video Course

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