J.Doe J.Doe - 2 months ago 7
Python Question

Reading 3 columns of data from .txt into list

Hello I have a question here. I have the following text file (3 columns and space between). I want to insert each column(tt,ff,ll) into it's own list(time,l,f).

Text file:

0.0000000000000000 656.5342434532456082 0.9992059165961109
1.0001828508431749 656.5342334512754405 1.0009810769697651
2.0003657016863499 656.5342259805754566 0.9989386155502871
3.0005485525295246 656.5342339081594218 1.0005032672779635
4.0007314033726997 656.5342356101768928 0.9996101946453564
5.0009142542158749 656.5342236489159404 0.9986884414684027
6.0010971050590491 656.5342474828242985 1.0001061182847479
7.0012799559022243 656.5342355894648563 1.0003982380731031
8.0014628067453994 656.5342256832242356 0.9993176599964499
9.0016456575885737 656.5342218575017341 0.9999117456245585
10.0018285084317498 656.5342408970133192 1.0000973751521087
11.0020113592749240 656.5342243211601954 0.9997189612768125
12.0021942101180983 656.5342320396634932 0.9997487346699927
13.0023770609612743 656.5342291293554808 0.9991986731183715


But I want the following output:

time: (0.00,1.00,2.003,4.0007 etc...)
l: (656.53,656.53,656.53,656.53 etc..)
f: (...)


Attempt code:

from numpy import *



def read_file(filename):
time = [] # list time
f = [] # ...
l = [] # ...
infile = open(filename, "r") # reads file
for line in infile: # each line in txt file
numbers = line.split() # removes the " "
tt = numbers[0] # 1st column?
ff = numbers[1] # 2nd column?
ll = numbers[2] # 3rd column?


time.append(tt) # Inserts 1st column(tt) into list(time)
f.append(ff) # ...
l.append(ll) # ...

return time,f,l # return lists

txt1 =read_file("1.txt") # calls function
print txt1 # print return values

Answer

use the loadtxt function of numpy

text_array = np.loadtxt('my_file.txt')
time = text_array[:, 0]
l = text_array[:, 1]
f = text_array[:, 2]