简体   繁体   中英

Transferring CSV file to a Python list

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.

This should do the trick:

import csv

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

print(M[0])

Another option is numpy.genfromtxt , eg:

import numpy as np
data = np.genfromtxt("yourfile.dat",delimiter=",")

This will make data a numpy array with as many rows and columns as are in your file

M is actually a iterable, not a list. You can use following

next(M)

or

l=[k for k in M]
print l[0]

Edited for @Eric's tip on deprecation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM