Reputation: 197
I have a CSV file in the same directory as my Python script, and I would like to take that data and turn it into a list that I can use later. I would prefer to use Python's CSV module. After reading the the module's documentation and questions regarding it, I have still not found any help.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import csv
inputfile = 'inputfile.csv'
inputm = []
reader = csv.reader(inputfile)
for row in reader:
inputm.append(row)
point1,point2,point3,point4
0,1,4,1
0,1,1,1
0,1,4,1
0,1,0,0
0,1,2,1
0,0,0,0
0,0,0,0
0,1,3,1
0,1,4,1
It only returns the string of the filename I provide it.
[['i'], ['n'], ['p'], ['u'], ['t'], ['f'], ['i'], ['l'], ['e']]
I would like it to return each row of the CSV file as a sub-list instead of each letter of the filename as a sub-list.
Upvotes: 1
Views: 10301
Reputation: 3787
You need to open the file in read mode, read the contents! That is,
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import csv
inputfile = 'inputfile.csv'
inputm = []
with open(inputfile, "rb") as f:
reader = csv.reader(f, delimiter="\t")
for row in reader:
inputm.append(row)
Output:
[['point1,point2,point3,point4'], ['0,1,4,1'], ['0,1,1,1'], ['0,1,4,1'], ['0,1,0,0'], ['0,1,2,1'], ['0,0,0,0'], ['0,0,0,0'], ['0,1,3,1'], ['0,1,4,1']]
Upvotes: 3
Reputation: 30268
You actually need to open()
the file:
inputfile = open('inputfile.csv')
You may want to look at the with
statement:
with open('inputfile.csv') as inputfile:
reader = csv.reader(inputfile)
inputm = list(reader)
Upvotes: 1