Newbie question: Tuples and reading csv files

Steve Howell showell30 at yahoo.com
Mon Mar 29 11:34:32 EDT 2010


On Mar 29, 8:31 am, Gryff <gareth.s... at googlemail.com> wrote:
> Hi
>
> Its been 20 years since I programmed, so I'm stepping back in via
> Python. However I'm beating my brains on tuples/lists (what I used to
> know as arrays). I've fooled around with small code snippets and tried
> a few things, but I can't figure out how to grab elements of
> tuples ...
>
> For example, I'm reading in a small csv file like this:
>
> import csv
>
> csvfile = open("example.csv")
>
> #sniff the dialect
> dialect = csv.Sniffer().sniff(csvfile.read(1024))
> csvfile.seek(0)
>
> # get file in using reader method
>
> mylist=[]
> reader = csv.reader(csvfile, dialect)
>
> # grab the lines into a reader and pass to mylist
>
> for row in reader:
>
>     mylist.append(row)
>
> # now print something out to prove this worked
>
> print mylist[:3]
>
> and the output I get is:
>
> ['Date', 'Open', 'High', 'Low', 'Close', 'Volume', 'Adj Close']
> ['2010-03-05', '224.20', '230.70', '223.80', '228.30', '5051500',
> '228.30']
> ['2010-03-04', '223.00', '228.50', '220.50', '224.50', '4040500',
> '224.50']
>
> So far so good but not useful. My "mylist" has all the data in there,
> but I can only figure out how to get each line out!?!
> -> I want to get access to the individual items in each line. In my
> bad old days I'd have used an array and grabbed "mylist
> [row,item]" ...job done.

You are not too far:

mylist[row][item]

If you try that and still get an error (unlikely), be sure to post the
exact code you tried and any error messages.




More information about the Python-list mailing list