1

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.

Code

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import csv
inputfile = 'inputfile.csv'

inputm = []

reader = csv.reader(inputfile)

for row in reader:
    inputm.append(row)

inputfile.csv

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.

2
  • can you share the contents of your csv Commented Mar 27, 2017 at 3:42
  • point1,point2,point3,point4 0,1,4,1 0,1,1,1 0,1,4,1 0,1,0,00,1,2,1 0,0,0,0 0,0,0,0 0,1,3,1 0,1,4,1 Commented Mar 27, 2017 at 3:53

2 Answers 2

3

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']]
Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.