Working with CSV files in Python

In this article we will look into how to read and write CSV files in python.

What is a CSV file?

The table below shows the names of three people living in three different cities.

SN Name City
1 Michael New Jersey
2 Jack California
3 Donald Texas

We can represent the above table in CSV as :

SN, Name, City
1, Michael, New Jersey
2, Jack, California
3, Donald, Texas

A CSV (comma separated values) file is a readable text file where each line has different fields separated by a comma.

We use CSV file to store tabular data like the one we saw above. We can think each line as a row and each field as a column.


How to read a CSV File in Python?

Python has inbuilt module i.e CSV, which is used for working with CSV files. In python, we use csv.reader module to read a CSV file.

Example : Reading a CSV file using csv.reader

Here we are going to show how you can read a people.csv file, that we created in above example.

import csv

with open('people.csv', 'r') as csvFile:
    reader = csv.reader(csvFile)
    for row in reader:
        print(row)

Once we run it on the python console, it will show following result :

['SN', 'Name', 'City']
['1','Michael', 'New Jersey']
['2','Jack', 'California']
['3','Donald', 'Texas']

In above program,

  • First, we open our CSV file as csvFile.
  • Then, we used the csv.reader() method to extract the data into the reader object which we can iterate over to get each line of our data.

How to write in a CSV File in Python?

In python, we use csv.Writer module to write in a csv file.

Example: Writing in a CSV file using csv.writer

Here we are going to show how you can write to in a csv file. We will output some data stored in a python list into a csv file.

import csv

csvData = [['Name of Person', 'Age'], ['Peter', '22'], ['Jasmine', '21'], ['Sam', '24']]

with open('person.csv', 'w') as csvFile:
    writer = csv.writer(csvFile)
    writer.writerows(csvData)

When we run the above program, person.csv will contain the following data

Name of Person, Age
Peter, 22
Jasmine, 21
Sam, 24

In the above code,

  • First, we created a list csvData with Name of Person and their Age.
  • Then we open the newly created person.csv file and insert csvData’s list into it.