Michael
Michael

Reputation: 16142

TypeError: '_csv.reader' object has no attribute '__getitem__' // getting columns?

I'm trying to open a .csv file and put each column in different list:

import csv
CSV = csv.reader(open("AAPL.csv","rb"))
column1 = CSV[0]
column2 = CSV[1]
column3 = CSV[2]
column4 = CSV[2]
column5 = CSV[4]
column6 = CSV[5]

Here is my AAPL.csv:

Date        Open    High    Low     Close   Volume   Adj Close
2013-09-27  874.82  877.52  871.31  876.39  1258800  876.39
2013-09-26  878.3   882.75  875     878.17  1259900  878.17
2013-09-25  886.55  886.55  875.6   877.23  1649000  877.23
2013-09-24  886.5   890.1   881.4   886.84  1467000  886.84
2013-09-23  896.15  901.59  885.2   886.5   1777400  886.5
2013-09-20  898.39  904.13  895.62  903.11  4345300  903.11
2013-09-19  905.99  905.99  895.4   898.39  1597900  898.39
2013-09-18  886.35  903.97  883.07  903.32  1934700  903.32
2013-09-17  887.41  888.39  881     886.11  1259400  886.11
2013-09-16  896.2   897     884.87  887.76  1336500  887.76
.............................................................
end of file:
.............................................................
2012-06-29  574.96  58013   572.20  580.07  2519500  580.07
2012-06-28  565.90  566.23  557.21  564.31  1920900  564.31
2012-06-27  567.70  573.99  566.02  569.30  1692300  569.30
2012-06-26  562.76  566.60  559.48  564.68  1350200  564.68
2012-06-25  567.33  568.09  557.35  560.70  1581600  560.70

When I run my code, it returns me the following error:

Traceback (most recent call last):
  File "/home/misha/Documents/finance/prices/some_csv.py", line 3, in <module>
    column1 = CSV[0]
TypeError: '_csv.reader' object has no attribute '__getitem__'

Is there any pythonic way to open a .csv file and put each column in different list not using attribute getitem?

Thanks.

NOTE: and also i need to skip first row.

Upvotes: 0

Views: 4587

Answers (2)

Mukesh Chapagain
Mukesh Chapagain

Reputation: 25968

This should work:

import csv
CSV = csv.reader(open("AAPL.csv","rb"))
for col in CSV:
    column1 = col[0]    
    column2 = col[1]
    column3 = col[3]

Upvotes: 0

Blckknght
Blckknght

Reputation: 104712

A csv.reader instance is an iterable over the lines of the CSV file. If you want each column in a separate list, you can use the zip function:

import csv

with open("AAPL.csv", "rb") as f:
    CSV = csv.reader(f)

    header = next(CSV) # read the header row
    column_data = zip(*CSV) # read data and arrange by columns instead of by rows

# do stuff with column_lists

Note that this reads the whole file in at once. If you have a very large amount of data in your file, you might want to redesign your algorithms to work on the data one row at a time as you iterate over the CSV object, so you don't need to hold it all in memory.

Upvotes: 3

Related Questions