[Tutor] Reading in data

Kirby Urner urnerk@qwest.net
Tue, 16 Apr 2002 12:28:52 -0700


At 11:25 AM 4/16/2002 -0400, Cliff Martin wrote:
>I've noticed over the months that most of the posts are asking about
>text or text manipulation for the web. I'm interested in simple data
>manipulation of numbers.  In all the books I've read I've never seen one
>example of how to read into a variable 1) two columns(or three if I'm
>doing 3D) of numbers that represent an ordered pair(or set) without line
>feeds and 2) a simple stream of data over multiple lines without the
>line feeds.  Could I get some help here?  Also any references to using
>Python as a data cruncher would be useful. NumPy, etc. is nice but most
>of the work there is associated with modeling not analyzing data.
>Thanks in advance.
>
>Cliff



  >>> f = open("test.dat",'w')
  >>> f.writelines(
  """
  3.0  4.5  3.1
  1.4  2.1  4.5
  """)
  >>> f.close()
  >>> f = open("test.dat",'r')
  >>> for i in f.readlines(): print i,


  3.0  4.5  3.1
  1.4  2.1  4.5

  >>> def getdata(filename):
          f = open(filename,'r')
          xyz = []  # empty list
          for i in f.readlines():
             if len(i.strip())>0:  # skip blank lines
                 xyz.append([float(x) for x in i.split()]) # str->floats
          return xyz

  >>> getdata("test.dat")
  [[3.0, 4.5, 3.1000000000000001], [1.3999999999999999,
  2.1000000000000001, 4.5]]


Kirby