Reading a tab delimited text file.
Tim Chase
python.list at tim.thechases.com
Mon Feb 23 17:45:12 EST 2009
>> 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
More information about the Python-list
mailing list