Search code examples
pythonpython-3.xappendbiopython

Python: How do I append (add a single character) to the end of the first line of a txt or phylip file


I have a phylip file that looks like this (only showing first 3 lines):

           6   39

 Archaeopt   CGATGCTTACCGCCGATGCT

 Hesperorni   CGTTACTCGTTGTCGTTACT

But I want to add "I" right behind the integer 39. How can I go about this? I have tried using append but it adds it to the end of the file which isn't what I want. Thanks. I want it to look like this:

            6   39I

 Archaeopt   CGATGCTTACCGCCGATGCT

 Hesperorni   CGTTACTCGTTGTCGTTACT

Here's is what I did:

       aln = open(r"C:\Users\Idowu\Downloads\paml\ref.phy","a")
       aln.write("I")
       aln.close()

And this was the outcome:

6   39
Archaeopt   CGATGCTTAC CGCCGATGCT
Hesperorni   CGTTACTCGT TGTCGTTACT
Baluchithe   TAATGTTAAT TGTTAATGTT
B. virgini   TAATGTTCGT TGTTAATGTT
Brontosaur   CAAAACCCAT CATCAAAACC
B.subtilis   GGCAGCCAAT CACGGCAGCC

TACCGCCGAT GCTTACCGC
CGTTGTCGTT ACTCGTTGT
AATTGTTAAT GTTAATTGT
CGTTGTTAAT GTTCGTTGT
CATCATCAAA ACCCATCAT
AATCACGGCA GCCAATCACI

As you would notice the I was added at the end.


Solution

  • with open('1.txt') as f:
        data = f.readlines()
    
    
    data1 = data[0].split('\n')
    data1[0] = data1[0] + 'I'
    
    data[0] = ''.join(data1[0]) + '\n'
    
    with open('1.txt','w') as f:
        for i in data:
            f.write(i)
    
    • First two lines of code reads all lines in files and stores each line of file in form of list.
    • Next three line of code takes first line of file and append 'I' to it.
    • And last three lines override the data in file and you get your desired result