[Solved] 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)

Enquirer: pafpaf

||

Solution #1:

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

Respondent: Dennis Sakva

Solution #2:

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])
Respondent: Karim Tabet

Solution #3:

That is a 2D array!

Can index it like this:

data[row][value]

For example, do get the IP address of the second line in your CSV:

data[1][2]
Respondent: Jamie Cockburn

Solution #4:

say your indicies for ip_address, time, port are

ip_address = 2         
time = 3               
port = 11              
print [[item[ip_address], item[time], item[port]] for item in data]      

output

[['192.168.4.118', '1605', 'Jun 15, 2010 18:27:57.490835000'], 
 ['115.85.145.5', '80', 'Jun 15, 2010 18:27:57.493200000'], 
 ['115.85.145.5', '80', 'Jun 15, 2010 18:27:57.496713000']]

you can do this when appending rows into data itself

for row in data reader:
    data.append([row[ip_address], row[time], row[port]])   
Respondent: Ashoka Lella

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published.