JeyKey
JeyKey

Reputation: 423

How to read csv file lines and split elements in line into list of lists?

I have csv file. When I open it by VisualStudio, i have something like this:

nr1  nr2  nr3  name  place
10  01  02  Jack  New York
10  01  03  David  London
10  02  01  Jasmine  New Jersey

There are two spaces between elements in every line and one space in name of the place.

When I open csv file by Excel, there are just elements in every other column.

I don't know how can I read this csv file to make every line a list of elements like this:

my_list = [

['10','01','02','Jack','New York']
['10','01','03','David','London']
['10','02','01','Jasmine','New Jersey']]

Cause I want to make some loop after this:

for line in my_list:
     nr1 = line[0]
     nr2 = line[1]
     nr3 = line[2]
     name = line[3]
     place = line[4]

And here I will make an instance of the class for every line.

How can I do that?

Upvotes: 0

Views: 36111

Answers (4)

Ajax1234
Ajax1234

Reputation: 71451

Try this, using the csv module and its reader() method:

import csv

f = open('file.csv')

the_data = list(csv.reader(f, delimiter r'\t'))[1:]

Upvotes: 3

martineau
martineau

Reputation: 123413

Using the csv module makes doing it fairly easy. The only trick was to make the two-letter delimiter used in the input file appear to be a single character, ',', in the example, because it the default.

import csv
from pprint import pprint

with open('my_data.csv', 'r', newline='') as csv_file:
    reader = csv.reader(line.replace('  ', ',') for line in csv_file)
    my_list = list(reader)
    pprint(my_list)

Output:

[['nr1', 'nr2', 'nr3', 'name', 'place'],
 ['10', '01', '02', 'Jack', 'New York'],
 ['10', '01', '03', 'David', 'London'],
 ['10', '02', '01', 'Jasmine', 'New Jersey']]

Upvotes: 1

Haha TTpro
Haha TTpro

Reputation: 5546

They are tab delimited csv file. Meaning that each column is separated by tab ('\t').

The following code should work.
Updated: use .rstrip() to remove \n

import csv

f = open('data.csv')

data = []
for line in f:
    data_line = line.rstrip().split('\t')
    data.append(data_line)

print data

Upvotes: 2

Nipun Garg
Nipun Garg

Reputation: 658

Try this

with open("file.csv","r") as file:
   data = file.read()

data = data.strip(' ').split('\n')

for i in len(data):
   data[i] = data[i].strip(' ').split(',')
   for j in len(data[i]):
      data[i][j] = data[i][j].strip(' ')
print (data)

Upvotes: 0

Related Questions