2012-09-17 34 views
1

我是一個絕對的編程新手,試圖與一些CSV文件一起工作。雖然我想要做的總體上是更復雜的,我目前堅持在這個問題上:如何遍歷目錄中的csv文件並將值寫入二維列表?

我有csv文件包含固定數量的'列'和可變數量的行。我想要做的是在目錄中打開每個csv文件,而在內存中將文件值存儲到2d列表中,然後從該列表中拉出一列「數據列」。通過在循環中這樣做,我可以在每個csv文件中添加一列數據列。

當我做了一個文件,它的工作原理:

csvFile = 'testdata.csv' 
currentFile = csv.reader(open(csvFile), delimiter=';') 
errorValues = [] 

    for data in currentFile: 

     rows = [r for r in currentFile] #Store current csv file into a 2d list   
     errorColumn = [row[34] for row in rows] #Get position 34 of each row in 2D list 
     errorColumn = filter(None, errorColumn) #Filter out empty strings 
     errorValues.append(errorColumn) #Append one 'column' of data to overall list 

當我嘗試循環它在我的目錄中的所有文件,我得到一個「列表索引超出範圍」的錯誤:

dirListing = os.listdir(os.getcwd())  
errorValues = [] 

for dataFile in dirListing: 
    currentFile = csv.reader(open(dataFile), delimiter=';')   

    for data in currentFile: 

     rows = [r for r in currentFile] #Store current csv file into a 2d list   
     errorColumn = [row[34] for row in rows] #Get position 34 of each row in 2D list 
     errorColumn = filter(None, errorColumn) #Filter out empty strings 
     errorValues.append(errorColumn) #Append one 'column' of data to overall list 

    errorColumn = [] #Clear out errorColumn for next iteration 

錯誤發生在'errorColumn = [row [34] for row in rows]''。我嘗試了各種方式來做到這一點,總是失敗索引超出範圍的錯誤。錯誤不在我的csv文件中,因爲我已經使用工作腳本逐個測試它們。可能是什麼問題呢?

非常感謝您的幫助。

+0

你在'currentFile'上循環,然後再次在循環內循環'currentFile'?這不會做你期望的事情。 –

回答

1

for循環穿過CSV文件的行。每行都由閱讀器轉換爲元素行。這樣,循環中的data已經是該行。下一個構造也遍歷打開的文件。這是錯誤的。

您的open()存在問題。該文件必須以二進制模式打開(在Python 2中)。

嘗試以下(我並沒有把一切你想要的內線):

dirListing = os.listdir(os.getcwd())  
errorValues = [] 

rows = []     # empty array of rows initially 

for fname in dirListing: 
    f = open(fname, 'rb') # open in binary mode (see the doc) 
    reader = csv.reader(f, delimiter=';')   

    errorColumn = []  # initialized for the file 

    for row in reader: 
     rows.append(row) #Store current csv file into a 2d list   
     if len(row) > 34: 
      errorColumn.append(row[34]) #Get position 34 of each row in 2D list 

    errorValues.append(errorColumn) 

    f.close()    # you should always close your files 

當心! os.listdir()也返回子目錄的名稱。嘗試添加

if os.path.isfile(fname): 
    ... 

順便說一句,您應該清楚地描述您的實際目標是什麼。可能有更好的方法來解決它。您可能在思維上固定於首先想到的解決方案。利用這些媒體有更多的眼睛和更多的建議解決方案。

+0

非常感謝您的幫助。這幾乎完全是我想要做的。看起來我仍然有很多東西要學習python中的簡單東西。 – foushad

+0

我很高興可以幫忙;) – pepr

2

我有點驚訝你提到的錯誤是在[r for r in currentFile]。在最壞的情況下,您的rows列表將爲空...

您是否100%確定全部您的線路是否至少有35列?你在哪裏沒有空行?在最後?這是值得檢查是否

errorColumn = [row[34] for row in rows if row] 

仍然給出了一個錯誤。前提是你擺脫了for data in currentFile行的第一個(你不使用,更重要的消耗你的currentFile,留給你rows==[]

+0

哦,我犯了一個愚蠢的錯誤。錯誤發生在「errorColumn = [row [34]行中的行]」,我已經在主文章中解決了這個問題。 – foushad

+0

確定文件沒問題,我已經單獨檢查了它們中的每一個。 – foushad

相關問題