Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reading CSV file and inserting it into 2d list in python

I want to insert the data of CSV file (network data such as: time, IP address, port number) into 2D list in Python.

Here is the code:

import csv
datafile = open('a.csv', 'r')
datareader = csv.reader(datafile, delimiter=';')
data = []
for row in datareader:
    data.append(row)    
print (data[1:4])

the result is:

[['1', '6', '192.168.4.118', '1605', '', '115.85.145.5', '80', '', '60', '0.000000000', '0x0010', 'Jun 15, 2010 18:27:57.490835000', '0.000000000'], 
['2', '6','115.85.145.5', '80', '', '192.168.4.118', '1605', '', '1514', '0.002365000', '0x0010', 'Jun 15, 2010 18:27:57.493200000', '0.002365000'], 
['3', '6', '115.85.145.5', '80', '', '192.168.4.118', '1605', '', '1514', '0.003513000', '0x0018', 'Jun 15, 2010 18:27:57.496713000', '0.005878000']]

But it is just one dimension and I don't know how to create 2D array and insert each element into the array.

Please suggest me what code should I use for this purpose. (I looked the previous hints in the website but none of them worked for me)

like image 592
pafpaf Avatar asked Jul 07 '14 08:07

pafpaf


People also ask

How do you read a csv file into an array in Python?

Use numpy. loadtxt() to Read a CSV File Into an Array in Python. As the name suggests, the open() function is used to open the CSV file. NumPy's loadtxt() function helps in loading the data from a text file.


2 Answers

Here's a clean way to get a 2D array from a CSV that works with older Python versions too:

import csv
data = list(csv.reader(open(datafile)))
print(data[1][4])
like image 94
Karim Tabet Avatar answered Oct 12 '22 22:10

Karim Tabet


You already have list of lists, which is sort of 2D array and you can address it like one data[1][1], etc.

like image 21
Dennis Sakva Avatar answered Oct 13 '22 00:10

Dennis Sakva