[Tutor] CSV question for getting data from a text file

Alan Gauld alan.gauld at btinternet.com
Mon Oct 19 03:15:04 CEST 2009

"Ara Kooser" <ghashsnaga at gmail.com> wrote

> testreader = csv.reader(open(filein))
> for row in testreader:
>    print(row)
> The output looks like this:
> []
> ['----------------------------Distribution of
> species----------------------------']
> []
> ['\t                                           Log       Log         Log 
> ']
> ['\tSpecies            Molality    Activity  Molality  Activity 
> Gamma']
> []
> ['\tOH-               4.121e-06 
> .489e-06    -5.385    -5.457    -0.072']
> How do ignore everything before and after the Distribution of species

You don't tell us how the "after species" is defined but the before bit
can be done with a flag that gets set when you hit the required line:

active = False
for row in testreader:
     if not actve and "Distribution" in row: active = True
     elif <Whatever detects the end os species>: active = False
           process species stuff here

> then pull out the species and activties so I can perform calculations on
> them? Is csv the best for that or am I better off using split and dumping
> into a dictionary? I think I need to specify white space as the 
> delimiter,
> is that correct?

You would need to specify whitespace. But in that case I suspect split
will work just as well. Whether you feed into a dictionary or just index
the list produced by split() depends on exactly what processing you
need to do to the results.


Alan Gauld
Author of the Learn to Program web site

More information about the Tutor mailing list