[Tutor] Extracting columns from CSV
Kent Johnson
kent37 at tds.net
Sun Oct 11 15:02:21 CEST 2009
On Sun, Oct 11, 2009 at 8:40 AM, Utkarsh "" <livinglif3 at gmail.com> wrote:
> Hello, I have a CSV file, from which I want to extract data.
> The CSV file is arranged like this:
> Time, InSec, Open, High, Low, Close, Qty
> 09:55:17,35717,41.95,41.95,41.95,41.95,105
> 09:56:03,35763,41.75,41.75,41.75,41.75,20785
> 09:56:40,35800,41.75,41.75,41.75,41.75,8950
> I wanted to extract each column, and put the data in a list, with a list for
> each column.
> I'm using the following code to perform this action:
> Time, InSec, Open, High, Low, Close, Volume = [], [], [], [], [], [], []
> thefile = open('somefile.CSV', 'r')
> linelist = thefile.readline()
> while linelist != '':
> b = linelist.split(',')
> Time.append(b[0])
> InSec.append(b[1])
> Open.append(b[2])
> High.append(b[3])
> Low.append(b[4])
> Close.append(b[5])
> Volume.append(b[6])
> linelist = thefile.readline()
> Is there any other, better and more pythonic way to do this ?
First, you should use the csv module to read CSV files, it will do the
splitting for you and correctly handle any quoted values.
Second, a simple way to transpose a list of list is to use zip(*list_of_lists).
Putting these together gives
import csv
f = csv.reader(open('somefile.CSV'))
Time, InSec, Open, High, Low, Close, Volume = zip(*f)
(Pretty cool BTW that *f works, I wasn't sure if it could take an
iterable instead of a sequence.)
Kent
More information about the Tutor
mailing list