Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transefrring .CSV file to a list in Python

Tags:

python

list

csv

I'm trying to get data from a CSV file to a list in Python. This is what I have so far:

import csv

with open('RawEirgrid2.csv','rb') as csvfile:
    M = csv.reader(csvfile, delimiter=',')

print(M[0])

I'm trying to print the first item in the list just confirm the code is working (it's currently not). I get the following error:

TypeError: '_csv.reader' object is not subscriptable

In every example I look at it appears it should be subscriptable, so I'm not sure whats going on.

like image 748
AwayFromMyDesk Avatar asked Aug 11 '13 18:08

AwayFromMyDesk


1 Answers

All of these will work:

with open('RawEirgrid2.csv', 'rb') as csvfile:
    reader = csv.reader(csvfile, delimiter=',')
    print next(reader)
with open('RawEirgrid2.csv', 'rb') as csvfile:
    reader = csv.reader(csvfile, delimiter=',')
    lines = list(reader)

print lines[0]
with open('RawEirgrid2.csv', 'rb') as csvfile:
    reader = csv.reader(csvfile, delimiter=',')
    for line in reader:
        print line
        break  # stop after the first line

The object returned by csv.reader is iterable, but not a sequence, so cannot be subscripted. Note that if you try to use reader outside of the with statement, the file will have been closed, and it will error - the file is not actually read until you ask for the lines.

like image 149
Eric Avatar answered Sep 29 '22 07:09

Eric