This is a test version of Biostars. For the public version, visit https://www.biostars.org.
Adding in a specific place to a file in python

I have a NEXUS file and want to add a block to it. The file looks like this:

#NEXUS
begin data;
    dimensions ntax=2 nchar=633;
    format datatype=dna missing=? gap=-;
matrix
22814 CATG---GACAGAGCGACCCGCG--CACGTTACAAACACTACGCGGGGTGGCCCCGGCTGCCTCGCGCGGAGGTGCTG---CT
11246 CATG---GACAGAGCGACCCGCGAACACGTTACAAACACTACGCGGGGTGGCCCCGGCTGCCTCGC--GGAGGTGCTG--GCT
;
end;

I'm using this code:

for x in ad:
    with open("nex.nexus", "a") as myfile:
        myfile.write("\n" + str(x))

And gets:

#NEXUS
begin data;
    dimensions ntax=2 nchar=633;
    format datatype=dna missing=? gap=-;
matrix
22814 CATG---GACAGAGCGACCCGCG--CACGTTACAAACACTACGCGGGGTGGCCCCGGCTGCCTCGCGCGGAGGTGCTG---CT
11246 CATG---GACAGAGCGACCCGCGAACACGTTACAAACACTACGCGGGGTGGCCCCGGCTGCCTCGC--GGAGGTGCTG--GCT
;
end;
22814 0 0 1 0 0
11246 0 1 0 0 1

I would like the last two lines to be added before the ";" on the 8th line. And finally get:

#NEXUS
begin data;
    dimensions ntax=2 nchar=633;
    format datatype=dna missing=? gap=-;
matrix
22814 CATG---GACAGAGCGACCCGCG--CACGTTACAAACACTACGCGGGGTGGCCCCGGCTGCCTCGCGCGGAGGTGCTG---CT
11246 CATG---GACAGAGCGACCCGCGAACACGTTACAAACACTACGCGGGGTGGCCCCGGCTGCCTCGC--GGAGGTGCTG--GCT
22814 0 0 1 0 0
11246 0 1 0 0 1
;
end;

Thanks for any answer.

python

1 answer

You can read the file and save the lines above your breakpoint as one variable and the lines below as another variable.

   with open("nex.nexus", "a") as myfile:
       lines = myfile.readlines()
    top = lines[:7]
    bottom = lines[7:]

You can then adjust the writing steps accordingly.

Only the ';' character it won't always be on the 8th line.

Ok, you can can use an enumerated loop through the lines to save that index to a variable for use in the above indexing step.

for e, line in enumerate(lines):
    if line.strip() == ";":
        idx = e
        break

.strip() method will get rid of any whitespace that might mess with your equivalence test. idx can be used like so:

 with open("nex.nexus", "a") as myfile:
     lines = myfile.readlines()
     top = lines[:idx]
     bottom = lines[idx:]

Log in to answer this question.