Read CSV

A CSV (Comma Separated Values) file is a file with values seperated by a comma. Its often used to import and export with databases and spreadsheets.

Values are mostly seperated by comma. Sometimes another character is used like a semicolon, the seperation character is called a delimiter.

Related Course:
Data Analysis in Python with Pandas

Read CSV with Pandas

Pandas is a data analysis library. If you work with data a lot, using pandas is way better.
Lets say you have a csv file containing nation statistics:

Country, Capital, Language, Currency
United States, Washington, English, US dollar
Canada, Ottawa, English and French, Canadian dollar
Germany, Berlin, German, Euro

We can read a csv with the lines:

import pandas as pd
import numpy as np

df = pd.read_csv('nations.csv')

for country in df['Country']:

Pandas works with dataframes which hold all data. Thats why we can use the rows like df[‘name’].

Read CSV

If you don’t want to use pandas, you can use the csv module to read csv files.
This is as simple as:

import csv

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

We can access individual cells like so:

for row in csvReader:

Previous Post Next Post

Cookie policy | Privacy policy | ©