How to read columns in python

Steve Holden steve at holdenweb.com
Tue Feb 24 08:17:28 EST 2009


Dhananjay wrote:
> Well,
> 
> The three columns are tab separated and there are 200 such rows having
> these 3 columns in the file.
> 
> First two columns are x and y coordinates and third column is the
> corresponding value.
> 
> I want to read this file as a matrix in which column1 correspond to
> row,  column2 corresponds to columns(in matrix) and column3 corresponds
> to value in the matrix.
> 
> 
> 
> -- Dhananjay
> 
> 
> 
> On Tue, Feb 24, 2009 at 12:18 PM, Chris Rebert <clp2 at rebertia.com
> <mailto:clp2 at rebertia.com>> wrote:
> 
>     On Mon, Feb 23, 2009 at 10:41 PM, Dhananjay
>     <dhananjay.c.joshi at gmail.com <mailto:dhananjay.c.joshi at gmail.com>>
>     wrote:
>     > I am bit new to python and programming and this might be a basic
>     question:
>     >
>     > I have a file containing 3 columns.
> 
>     Your question is much too vague to answer. What defines a "column" for
>     you? Tab-separated, comma-separated, or something else altogether?
> 
Try something like

f = open("datafile.txt", 'r')
x = []; y = []; val = []
for line in f:
    xx, yy, vv = line.split()
    x.append(float(xx))
    y.append(float(yy))
    val.append(float(vv))

Of course this is only one way to represent the data - as vectors of x,
y and val. If you just wanted a list of the data triples then you could
have written

f = open("datafile.txt", 'r')
values = []
for line in f:
   x, y, v = line.split()
   values.append(float(x), float(y), float(v))

regards
 Steve

-- 
Steve Holden        +1 571 484 6266   +1 800 494 3119
Holden Web LLC              http://www.holdenweb.com/




More information about the Python-list mailing list