I have a text file in the following format: File
What I am interested in is to have python go through the Atoms chunk of the file (lines 34 to 24033), isolate the 3rd column (which correspond to the atoms type), and perform the following operation:
- Isolate only atom type 2 and 4
- Randomly select a user-defined percentage from that list of atoms (e.g. randomly select 40% of type 2 and 4 atoms)
- Add 3 to those selected atoms (2->5, 4->7)
- Write the new file with the updated atom types
Unfortunately, I don't have a lot of knowledge of reading/writing text files in python and so far the only pseudo solution I was able to come up with is the following:
import numpy as np
import random
data = np.loadtxt('5mer_SA.data',skiprows=33,max_rows=(24032-32))
atomType = data[:,2]
reactive = []
for i in range(len(atomType)):
if atomType[i] == 2 or atomType[i] == 4:
x = atomType[i]
reactive.append(x)
reactive_array = np.array(reactive)
p = 0.5 #user defined perecentage
newType = np.zeros(int(len(reactive_array)*p))
for j in range(len(newType)):
newType[j] = random.choice(reactive_array)+3
What I am struggling is to put back modified atomTypes to the text file in the original position. Any suggestions will be greatly appreciated. My ideal goal would be just to have a function that takes as input the user-defined percentage and automatically perform all the mentioned operation generating a new text file as output.