How to read csv file lines and split elements in l

2019-08-23 05:13发布

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?

4条回答
Rolldiameter
2楼-- · 2019-08-23 05:25

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']]
查看更多
Ridiculous、
3楼-- · 2019-08-23 05:34

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
查看更多
We Are One
4楼-- · 2019-08-23 05:41

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)
查看更多
我欲成王,谁敢阻挡
5楼-- · 2019-08-23 05:46

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:]
查看更多
登录 后发表回答