Question: Adding in a specific place to a file in python
0
gravatar for adrian18_07
4 months ago by
adrian18_0710
adrian18_0710 wrote:

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 • 195 views
ADD COMMENTlink modified 4 months ago by geneticatt40 • written 4 months ago by adrian18_0710
0
gravatar for geneticatt
4 months ago by
geneticatt40
geneticatt40 wrote:

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 COMMENTlink written 4 months ago by geneticatt40

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

ADD REPLYlink modified 4 months ago • written 4 months ago by adrian18_0710

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 REPLYlink written 4 months ago by geneticatt40
Please log in to add an answer.

Help
Access

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.
Powered by Biostar version 2.3.0
Traffic: 1626 users visited in the last hour
_