Python列表的标题

时间:2015-03-08 20:59:36

标签: python csv

Python新手。我有csv数据,如下所示:

Record  Name    Cur     e12mo   e24mo   e48mo   state
3928    Joes    2000    200     400     0       CA,GA
1       Toms    19       1      2       0       AR,KS
1747    Mine    60       5      10      0       AR,CT
5023    Yours   5        12     24      0       FL
7041    Theirs  10       2      4       0       FL

从教程输入代码如下:

import numpy as np
import csv as csv

readdata = csv.reader(open('c:\MyData\BYLCsv.csv'))
for row in readdata:
    print(row)
data = []  
for row in readdata:
    data.append(row)
for row in data:
    print(row)
Header = data[0]
data.pop(0) 

“Header = data [0]”语句中的代码炸弹。一切都在那里。

2 个答案:

答案 0 :(得分:2)

在第一个循环中,您读取整个文件,之后文件指针不会重置:

import numpy as np
import csv as csv
with open('c:\MyData\BYLCsv.csv') as data:
    readdata = csv.reader(data)
    header = next(readdata)
    data = list(readdata)
print(header)
for row in data:
    print(row)

答案 1 :(得分:1)

尝试将所有内容放在一起:

import numpy as np
import csv as csv

readdata = csv.reader(open('c:\MyData\BYLCsv.csv'))
data = []  

for row in readdata:
    print(row)
    data.append(row)

for row in data:
    print(row)

Header = data[0]
data.pop(0) 

你试图在readdata迭代器上迭代两次,它只能被消耗一次