2013-05-26 45 views
0

我正在使用python 3.3。我有一個csv文件,但我只想將每行的最後一列用作列表。我能夠顯示這個,但我不能將它作爲列表存儲。 這是我使用的代碼。Python從csv的每一行的最後一列創建一個列表

my_list = [] 
with open(home + filePath , newline='') as f: 
    Array = (line.split(',') for line in f.readlines()) 
    for row in Array: 
      #this prints out the whole csv file 
      #this prints out just the last row but I can't use it as a list 
      print(', '.join(row)) 
      print(row[6]) 

    print(my_list) 

那麼我將如何去走每行的最後一列(行[6]),並把到這一點,我可以爲整數使用列表?

回答

2

使用csv模塊的易用性,然後列表的理解:

import csv 
import os 

with open(os.path.join(home, filePath), newline='') as f: 
    reader = csv.reader(f) 
    my_list = [row[-1] for row in reader] 

請注意,我用row[-1]挑出每一行的最後一個元素。

你的代碼永遠不會添加任何東西到my_list;一個my_list.append(row[6])本來可以解決這個問題。

+0

非常感謝您的工作。 – aldx1

相關問題