Parse last three numbers from .txt

49 views Asked by At

i would like to read from a .txt file, which contains the numbers:

0 0 0 -5.0 0.0 0.0
1 1 0 -5.0 0.0 5.0
2 2 0 0.0 0.0 -5.0
3 3 0 0.0 0.0 0.0
4 4 0 5.0 0.0 -5.0
5 5 0 5.0 0.0 5.0

I only need the last three numbers of each line. They represend x,y and z values. Furthermore I want
to store these coordinates to a Matrix, so that I can use the Matrix containing coordinates
of points. I hope you can help me, cause I'm new to this and I didn't find help in other questions

Joe

1

There are 1 answers

0
alecxe On

Read the file, iterate over lines, split each line by space, take last 3 elements using slice notation and cast the values to float:

data = []
with open('test.txt', 'r') as f:
    for line in f:
        data.append(map(float, line.split()[-3:]))

print data

prints:

[[-5.0, 0.0, 0.0],  
 [-5.0, 0.0, 5.0], 
 [0.0, 0.0, -5.0], 
 [0.0, 0.0, 0.0], 
 [5.0, 0.0, -5.0], 
 [5.0, 0.0, 5.0]]