Newbie Import two coloums of floating point data into python HOWTO

Andy Gimblett gimbo at ftech.net
Mon Mar 11 07:54:15 EST 2002


On Mon, Mar 11, 2002 at 04:22:48AM -0800, Andybee wrote:

> Can some one tell me how to import two coloumns of data in a ascii
> text file,into two arrays in python? I cant seem to work it out. The
> data is genereated in matlab and I want to import it into python

Let's say you data looks something like this:

1.0   5.0
2.0   10.2
3.1   13.4

etc.

Then here's one answer...  There are probably cleverer and more
efficient ways of doing this, but this one's pretty easy to understand
and so hopefully more suited to a newbie... :-)

I'm also not _quite_ answering your question, because you asked how to
get two seperate lists, one per column, whereas what this does is
return a list of tuples (one tuple per data line), which is how _I'd_
do it.  ;-) Easy to change to your way, anyway.

def foobar(filename):

    # We'll return a single list, consisting of 2-element tuples, one
    # per line in the data file.

    results = []

    # Open the input file and read the lines.  Note that this reads
    # them all in before continuing, and so would be unsuitable for a
    # large file.  Possible alternatives would involve using
    # readline() or xreadlines(), the investigation of which is left
    # as an exercise to the reader.  :-)
    
    input = open(filename)
    lines = input.readlines()

    # Now iterate over the lines, populating the result
    
    for line in lines:
        
        if not line.strip():
            # Skip blank line
            continue

        # Split the line up, convert the values to floats, add it to
        # the result set.
        
        (first, second) = line.split()
        row = (float(first), float(second))
        results.append(row)

    return results

BTW, if you haven't seen it yet, I'd heartily recommend that you work
through the python tutorial at:

    http://www.python.org/doc/current/tut/tut.html

This contains everything you'd need to answer your question/understand
the above, and a whole lot more.

HTH,

Andy

-- 
Andy Gimblett - Programmer - Frontier Internet Services Limited
Tel: 029 20 820 044 Fax: 029 20 820 035 http://www.frontier.net.uk/
Statements made are at all times subject to Frontier's Terms and
Conditions of Business, which are available upon request.




More information about the Python-list mailing list