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?
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.
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.
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.
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.
>>> 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']]
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