简体   繁体   English

将 CSV 文件传输到 Python 列表

[英]Transferring CSV file to a Python list

I'm trying to get data from a CSV file to a list in Python.我正在尝试将数据从 CSV 文件获取到 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 TypeError:“_csv.reader”对象不可下标

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. csv.reader返回的对象是可迭代的,但不是序列,所以不能下标。 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.请注意,如果您尝试在 with 语句之外使用reader ,则文件将被关闭,并且会出错 - 直到您请求这些行,文件才真正被读取。

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:另一种选择是numpy.genfromtxt ,例如:

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这将使data成为一个 numpy 数组,其中包含与文件中一样多的行和列

M is actually a iterable, not a list. M 实际上是一个可迭代的,而不是一个列表。 You can use following您可以使用以下

next(M)

or或者

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

Edited for @Eric's tip on deprecation.针对@Eric 的弃用提示进行了编辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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