Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read lines from a CSV variable into a multidimensional array in python?

The string looks like this:

x = '''"High";"10";"Assigned";"2012/06/12 10:11:02"
"Low";"20";"Assigned";"2012/06/12 10:11:02"
"Medium";"30";"Assigned";"2012/06/12 10:11:02"'''

I want it to be like this:

x = [
[High, 10, Assigned, 2012/06/12 10:11:02],
[Low, 20, Assigned, 2012/06/12 10:11:02],
[Medium, 30, Assigned, 2012/06/12 10:11:02]]

Whats the best way to parse this?

like image 333
patchie Avatar asked Jun 12 '12 14:06

patchie


People also ask

How to 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.

How to get structured data from CSV file in Python?

The open () is a built-in function for file handling in Python. Then we need CSV.reader () to get structured data from.csv files. data_CSV = csv.reader (file_CSV) A list is the most used and convenient data structure in python so converting CSV files data into a list makes the data manipulation easy.

What are data arrays in CSV files?

These types of files are used to store data in the form of tables and records. In these tables, there are a lot of columns separated by commas. One of the tasks in manipulating these CSV files is importing these files in the form of data arrays.

How do you read a CSV file line by line?

As you may have gleaned from the name of the first argument, it expects to receive an iterable, so you can also pass a list of CSV rows (as text). When we pass a file handle, csv.reader () treats it as an iterable and reads the entire file line by line. csv.reader () also returns an iterable.


1 Answers

>>> import csv
>>> result = [row for row in csv.reader(x.splitlines(), delimiter=';')]
>>> import pprint
>>> pprint.pprint(result)
[['High', '10', 'Assigned', '2012/06/12 10:11:02'],
 ['Low', '20', 'Assigned', '2012/06/12 10:11:02'],
 ['Medium', '30', 'Assigned', '2012/06/12 10:11:02']]
like image 96
San4ez Avatar answered Oct 26 '22 00:10

San4ez