Newbie question: Tuples and reading csv files

Kushal Kumaran kushal.kumaran+python at gmail.com
Mon Mar 29 11:42:37 EDT 2010


On Mon, Mar 29, 2010 at 9:01 PM, Gryff <gareth.sims 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. Try as I like and after *lots* of reading
> around, I can't figure out whether:
>
mylist is a list of lists. mylist[0] gives you the first list (the
row with the column headings, in your case). You can get the first
item in that list by mylist[0][0].
> a) I'm missing something...really...simple
> b) "You can't do that"  (and I should just use numpy and arrays?)
> c) errrr....
>> Like I said, basic/newbie question from a programmer who spent 20
> years away from it.
>
-- 
regards,
kushal


More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /