Reading a tab delimited text file.

harijay harijay at gmail.com
Mon Feb 23 18:37:36 EST 2009


You could also use the csv module

import csv
myfileobj = open("myfiletab.txt","read")
csv_read = csv.reader(myfileobj,dialect=csv.excel_tab)
myval1 = []
myval2 = []
myval3 = []
for line in csv_read:
# filter header and stuff using some criterion
    if len(line) = 3:
      myval1.append(line[0])
      myval2.append(line[1])
      myval3.append(line[2])


etc etc . The csv module defines a dialect excel_tab. Each line is
then parsed into an array . You can insert that array into another
array and have an array line mydata = [ [line1],[line2] ...]

Hopw this helps
harijay

On Feb 23, 5:45 pm, Tim Chase <python.l... at tim.thechases.com> wrote:
> >>    time_vec, ch1_vec, and_so_on = zip(*(
> >>      map(float, line.split())
> >>      for line in file('in.txt')))
>
> >> If this isn't homework, there are some less terse versions which
> >> are a bit easier on the eyes and less like some love-child
> >> between Perl and Python.
>
> > haha, no this isn't homework. I'm a mechanical engineering student
> > working on a research project and this program is for my personal use
> > to analyze the data.
>
> The "zip-star map-float" variant is a pretty unreadable way to go.
>
> The more readable versions look something like
>
>    data = [map(float, line.split()) for line in file('in.txt')]
>    time_vec = [bit[0] for bit in data]
>    ch1_vec = [bit[1] for bit in data]
>    and_so_on = [bit[2] for bit in data]
>
> or even
>
>    time_vec = []
>    ch1_vec = []
>    and_so_on = []
>    for line in file('in.txt'):
>      a,b,c = map(float, line.split())
>      time_vec.append(a)
>      ch1_vec.append(b)
>      and_so_on.append(c)
>
> which could also be written as
>
>    for line in file('in.txt'):
>      line = line.split()
>      time_vec.append(float(line[0]))
>      ch1_vec.append(float(line[1]))
>      and_so_on.append(float(line[2]))
>
> -tkc

Another way would be to use the csv module .

import csv
f = file.open("mytabfile.txt"



More information about the Python-list mailing list