2013-05-14 58 views
0

我有以下CSV文件: enter image description hereExcel的CSV幫助的Python

如何導入數字只爲在同一時間在Python一排的陣列?沒有日期,沒有字符串。

我的代碼:

import csv 

def test(): 
    out = open("example.csv","rb") 
    data = csv.reader(out) 
    data = [row for row in data] 
    out.close() 
    print data 

讓我更清楚。我不想要一個巨大的二維數組。我想導入第二行,然後操作數據,然後獲得第三行。我需要一個for循環,但我不確定csv是如何工作的。

+2

到目前爲止您嘗試過什麼?你看過[csv](http://docs.python.org/2/library/csv.html)模塊嗎? – 2013-05-14 16:46:17

+1

你有多少個?如果是這樣,你不能只刪除第一行和第一列嗎? – 2013-05-14 16:48:22

回答

0

試試這個:

with open('the_CSV_file.csv','r') as f: 
    box = f.readlines() 

result_box = [] 
for line in box[1:]: 
    items = line.split(';') # adjust the separator character in the CSV as needed 
    result_box.append(items[1:]) 

print result_box 
+0

謝謝,我只是改變了一下你的代碼,使它工作 – user1681664 2013-05-14 21:49:41

0
% <csv # just a silly CSV I got from http://secrets.d8u.us/csv 
Secret,Timestamp 
Forza la fiera!,1368230474 
American healthcare SUXXXXX,1368232342 
I am not sure if I wanna take the girl out again,1368240406 
I bred a race of intelligent penguin assassins to murder dick cheney. ,1368245584 
"I guess it is my mother's time of the month, as it were",1368380424 
i've seen walls breath,1368390258 

In [33]: %paste 
with open('csv', 'rb') as csvfile: 
     csv_reader = csv.reader(csvfile, dialect='excel') # excel may be the default, but doesn't hurt to be explicit 
     csv_reader.next() 
     for row in csv_reader: 
       array.append(row[1:]) 
## -- End pasted text -- 

In [34]: array 
Out[34]: 
[['1368230474'], 
['1368232342'], 
['1368240406'], 
['1368245584'], 
['1368380424'], 
['1368390258']] 
0

更正爲每@ DSM的評論

您應該結束了,你想在array什麼:

import csv 

with open('theFile.csv', 'r', encoding = 'utf8') as data: 
    reader = csv.reader(data) 

    array = [] 
    next(reader) # skips 'string's row 
    for row in reader: 
     numberRow = [float(x) for x in row[1:]) # This slice skips 'date's 
     array.append(numberRow) 

我不確定是否有必要定義編碼。但是如果你想把它們當成數字,你將不得不使用float(x),否則它們只會是字符串。

+1

這不會像書面工作,因爲你不能切片'csv.reader'實例。我認爲通常的習慣用語是'下一個(讀者)',然後是通常的'在讀者行中'。 – DSM 2013-05-14 17:17:38

+0

謝謝@DSM。我原來的答案是'在閱讀器[1:]中排'而不在'下一個(閱讀器)' – mrKelley 2013-05-14 17:22:40