Adding in a specific place to a file in python
1
0
Entering edit mode
3.6 years ago
adrian18_07 ▴ 10

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 • 772 views
ADD COMMENT
0
Entering edit mode
3.6 years ago
geneticatt ▴ 140

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.

ADD COMMENT
0
Entering edit mode

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

ADD REPLY
0
Entering edit mode

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:]
ADD REPLY

Login before adding your answer.

Traffic: 1833 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6