0

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:

  1. Isolate only atom type 2 and 4
  2. Randomly select a user-defined percentage from that list of atoms (e.g. randomly select 40% of type 2 and 4 atoms)
  3. Add 3 to those selected atoms (2->5, 4->7)
  4. 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.

  • "Unfortunately, I don't have a lot of knowledge of reading/writing text files in python" Did you try googling "write text file python" or "write text file numpy"? – Code-Apprentice Feb 22 '22 at 20:16
  • Yes, I have a minimum knowledge of writing text file and reading text files, however, I am more familiar with manipulating arrays using NumPy and I am struggling to do the mathematical operations I need to do when reading strings – Alessandro Perego Feb 22 '22 at 20:44
  • The related links suggest https://stackoverflow.com/questions/39086/search-and-replace-a-line-in-a-file-in-python might be relevant? – Andrew McClement Feb 22 '22 at 22:29
  • @AndrewMcClement, thank you so much for the link. I came across something similar while waiting for an answer here. I am able to read and find or replace specific text in the file, however I am struggling to perform mathematical operations when I read the text as a string using readlines(), I can't figure out a way to read the text, transform it through mathematical operations and write it back to the original file (or to a new file). Additionally, when I read line by line the text file, I am not able to isolate just the column I need even when I transform the string to an array. – Alessandro Perego Feb 22 '22 at 22:40

0 Answers0