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)
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.
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])
You already have list of lists, which is sort of 2D array and you can address it like one data[1][1], etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With