Search code examples
pythonarraysreplacelines

replacing lines in file


I have a file that looks like this (columns ar coordinates x,y,z and lines represents some objects):

 1.02      0.63      0.0003 
-1.34      0.61      0.0002
 0.0       0.0       0.0
-1.91      0.25      0.87
-1.32      1.70      0.0
 0.02     -1.12     -0.06 

I want to:

1) multiply second line by 3;

2) find the differences between new values in line 2 and old valuesn(those I got by multiplying) in the same columns (i.e. the difference between second line's column one new value and old value, secons line's column two new value and old etc.)

3)replace values in line 2 by new values;

4) add the differences I got to the values in lines 4 and 5.

So the output should look like:

 1.02      0.63      0.0003
-4.02      1.83      0.0006
 0.0       0.0       0.0
-4.59      1.47      0.8704
-4.00      2.92      0.0004
-2.66      0.10     -0.0596

What I got so far is:

import numpy as np 

a=np.loadtxt('geometry.in')
C=s[1]
b=np.array((a)[C]) #read second line as array
x_old=b[0] #define coordinate x
y_old=b[1] #define coordinate y
z_old=b[2] #define coordinate z

C_new=b*3 #multiplying all line by 3

x=C_new[0] #defining new values in columns of the line
y=C_new[1]
z=C_new[2]

dx=x-x_old #the differene that I need to add to the first column of lines 4 and 5
dy=y-y_old
dz=z-z_old

I tried a.replace(x_old, x) but it didn't work and I got really stuck in this.


Solution

  • If you have to use numpy, here is an example you can work on: load the whole data as a numpy array "ao"

        old2 = ao[1,:]
        new2 = ao[1,:]*3
        diff = new2 - old2
        ao[1,:] = new2
        ao[3:,:] = ao[3:,:] + diff