Search code examples
pythontext

Copying text from file into another and edit resulting file


I'm trying to write a function that will generate a series of files using text from another file. The issue I'm having is that I want to add text to the end of the line that was written from file. In addition to this, I want the added text to be dependent on what line I'm in.

The source file looks something like this:

C1      1.00964527   -0.31216598   -0.03471416
C2      2.46197796   -0.03537534   -0.02239528
C3      3.13892016   -1.29949550   -0.01824029
N1      0.78031101   -1.74687208   -0.03258816
N2      2.41533961   -3.71674253   -0.03080008
H1      6.38746003   -0.16735186    0.01037509
H2      5.06643233   -2.35376889   -0.00392019
H3      2.64230377    2.15284044   -0.01822299
Cu1    -0.97960685   -2.67533229   -0.06199922

The goal is to generate an output file that has two columns additional columns at the end where the values of the new columns would be determined via inputs to the function.

C1      1.00964527   -0.31216598   -0.03471416  6 32
C2      2.46197796   -0.03537534   -0.02239528  4 32
C3      3.13892016   -1.29949550   -0.01824029  4 32
N1      0.78031101   -1.74687208   -0.03258816  7 32
N2      2.41533961   -3.71674253   -0.03080008  7 32
H1      6.38746003   -0.16735186    0.01037509  1 32
H2      5.06643233   -2.35376889   -0.00392019  1 32
H3      2.64230377    2.15284044   -0.01822299  1 32
Cu1    -0.97960685   -2.67533229   -0.06199922 29 32

The following portion of the code copies the contents of the source file and pastes them onto the output file.

def makeGNDrun(fname, aname, nAtoms):
    i = 1
    for i in range(1, nAtoms + 1):

        f = open(str(aname) + str(i) + "_gnd.run", "w+")

        with open(fname + ".xyz") as f:
            with open(aname + str(i) + "_gnd.run", "a+") as f1:
                for line in f:
                    f1.write(line)

I'm unsure as to how to add the last two columns however.


Solution

  • If I understood your question correctly, then you can do something like that:

    def makeGNDrun(fname, aname, nAtoms):
        for i in range(1, nAtoms + 1):
    
            # open two files together... first in read-mode and the other in append-mode
            with open(str(aname) + str(i) + "_gnd.run", "r") as f, \
                 open(aname + str(i) + "_gnd.run", "a") as f1:
    
                 # iterate over lines of f which is in read-mode
                 for line in f.readlines():
                     # line is read from f, so you can modify it before writting it to f1
                     # here I will append " i  32" to it
                     line = line.strip() + '\t' + str(i) + '\t' + str(32) + '\n'
                     f1.write(line)
    

    Hopefully, this is what you meant!!