我是一個絕對的編程新手,試圖與一些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文件中,因爲我已經使用工作腳本逐個測試它們。可能是什麼問題呢?
非常感謝您的幫助。
你在'currentFile'上循環,然後再次在循環內循環'currentFile'?這不會做你期望的事情。 –