feniix
feniix

Reputation: 1628

How to read lines from a file into a multidimensional array (or an array of lists) in python

I have a file with a format similar to this:

a,3,4,2,1
3,2,1,a,2

I want to read the file and create an array of lists

in a way that:

array[0] = ['a','3','4','2','1']
array[1] = ['3','2','1','a','2']

How can I do that?

So far I am stuck with:

f = open('./urls-eu.csv', 'r')
for line in f:
    arr = line.split(',')
print arr

I am really new to python.

Upvotes: 4

Views: 10041

Answers (2)

kurosch
kurosch

Reputation: 2312

Batteries included:

>>> import csv
>>> array = list( csv.reader( open( r'./urls-eu.csv' ) ) )
>>> array[0]
['a', '3', '4', '2', '1']
>>> array[1]
['3', '2', '1', 'a', '2']

Upvotes: 16

SilentGhost
SilentGhost

Reputation: 319561

you're almost there, you just need to do:

arr = [line.split(',') for line in open('./urls-eu.csv')]

it iteratively process file line by line, splits each line by comma and accumulates resulting lists into a list of lists. you can drop opening mode ('r') since it's a default one.

Upvotes: 7

Related Questions