Iterate over CSV rows in Python


Given CSV file file.csv:

column1,column2
foo,bar
baz,qux

You can loop through the rows in Python using library csv or pandas.

csv

Using csv.reader:

import csv

filename = 'file.csv'

with open(filename, 'r') as csvfile:
    datareader = csv.reader(csvfile)
    for row in datareader:
        print(row)

Output:

['column1', 'column2']
['foo', 'bar']
['baz', 'qux']

Repl.it demo:

pandas

Install pandas:

$ pip install pandas

Using pandas.read_csv and pandas.DataFrame.iterrows:

import pandas as pd

filename = 'file.csv'
df = pd.read_csv(filename)

for index, row in df.iterrows():
    print(row)

Output:

column1    foo
column2    bar
Name: 0, dtype: object
column1    baz
column2    qux
Name: 1, dtype: object

Repl.it demo:



If you enjoyed this post, please consider supporting this site!