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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With