DEV Community

Cover image for Read CSV in Python
bluepaperbirds
bluepaperbirds

Posted on

Read CSV in Python

A csv file is a file in which data is separated by a delimiter (often a comma). Many office programs can store data in a csv format (Google Sheet, Microsoft Excel etc).

The file format is just that simple: a bunch of data which is divided using a delimiter (sometimes called the separator). Example CSV file data:

1/2/2020,5,5,8,white
1/3/2020,3,5,2,blue
1/4/2020,2,9,1,green

CSV only stores data (values), not formatting. So if you save as a csv file, you lose all formatting you had before. Now for Python programs, formatting is totally irrelevant.

csv file loses formatting

read csv

In Python, you can read a csv file. You can then use its data in your program. There are several ways to read a csv file with Python.

  • without any module
  • read with csv module
  • read with pandas module module

To read a csv without any module, read the file first and then use the split function with delimiter to extract values (txt.split(",")).

If you deal with data a lot, I recommend to use the Pandas module. Pandas is a fast, powerful, flexible and easy to use open source data analysis and manipulation tool, built on top of the Python programming language.

You can use pandas to read other data sources too (like excel). A good course for Pandas is data analysis with pandas

csv module

With the csv module you can read a csv file like this. First import the csv module. Then read the file, define the delimiter and iterate row by row.

import csv

with open('example.csv') as csvfile:
    csvfile = csv.reader(csvfile, delimiter=',')
    for row in csvfile:
        print(row)

Every row is a list of values in the csv file.

$ python3 example.py 
['1/2/2020', '5', '5', '8', 'white']
['1/3/2020', '3', '5', '2', 'blue']
['1/4/2020', '2', '9', '1', 'green']

Related links:

Top comments (0)