Python Code - How To Read CSV into an Array of Arrays

October 05, 2021

Introduction

In last post, we saw How to read CSV with Headers into Dictionary

In this post, we will read the csv data into array of arrays.

Lets assume we have a csv something similar to following:

firstname,lastname,address,city,state,pin
John,Doe,120 jefferson st.,Riverside, NJ, 08075
Jack,McGinnis,220 hobo Av.,Phila, PA,09119
"John ""Da Man""",Repici,120 Jefferson St.,Riverside, NJ,08075
Stephen,Tyler,"7452 Terrace ""At the Plaza"" road",SomeTown,SD, 91234
,Blankman,,SomeTown, SD, 00298
"Joan ""the bone"", Anne",Jet,"9th, at Terrace plc",Desert City,CO,00123

Python code to read CSV into Array of Dictionary

def read(filepath):
  content = []
  with open(filepath) as csvfile:
    csv_reader = csv.reader(csvfile)

    for row in csv_reader:
      content.append(row)

  return content

content = read("addresses.csv")
print(content)

The Output as Array of Dictionary

[
  ['John', 'Doe', '120 jefferson st.', 'Riverside', ' NJ', ' 08075'],
  ['Jack', 'McGinnis', '220 hobo Av.', 'Phila', ' PA', '09119'],
  ['John "Da Man"', 'Repici', '120 Jefferson St.', 'Riverside', ' NJ', '08075'],
  ['Stephen', 'Tyler', '7452 Terrace "At the Plaza" road', 'SomeTown', 'SD', ' 91234'],
  ['', 'Blankman', '', 'SomeTown', ' SD', ' 00298'],
  ['Joan "the bone", Anne', 'Jet', '9th, at Terrace plc', 'Desert City', 'CO', '00123']
]

Hope it helps.


Similar Posts

Latest Posts