Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I reverse compliment a multiple sequence fasta file with python?

I am new to python and I am trying to figure out how to read a fasta file with multiple sequences and then create a new fasta file containing the reverse compliment of the sequences. The file will look something like:

>homo_sapiens ACGTCAGTACGTACGTCATGACGTACGTACTGACTGACTGACTGACGTACTGACTGACTGACGTACGTACGTACGTACGTACGTACTG

>Canis_lupus CAGTCATGCATGCATGCAGTCATGACGTCAGTCAGTACTGCATGCATGCATGCATGCATGACTGCAGTACTGACGTACTGACGTCATGCATGCAGTCATG

>Pan_troglodytus CATGCATACTGCATGCATGCATCATGCATGCATGCATGCATGCATGCATCATGACTGCAGTCATGCAGTCAGTCATGCATGCATCAT

I am trying to learn how to use for and while loops so if the solution can incorporate one of them it would be preferred.

So far I managed to do it in a very unelegant manner as follows:

file1 = open('/path/to/file', 'r')

for line in file1:
   if line[0] == '>':
      print line.strip() #to capture the title line
   else:
      import re
      seq = line.strip()
      line = re.sub(r'T', r'P', seq)
      seq = line
      line = re.sub(r'A',r'T', seq)
      seq = line
      line = re.sub(r'G', r'R', seq)
      seq = line
      line = re.sub(r'C', r'G', seq)
      seq = line
      line = re.sub(r'P', r'A', seq)
      seq = line
      line = re.sub(r'R', r'C', seq)
      print line[::-1]

file1.close()

This worked but I know there is a better way to iterate through that end part. Any better solutions?

like image 626
scooterdude32 Avatar asked Jul 21 '26 14:07

scooterdude32


1 Answers

Assuming I got you right, would the code below work for you? You could just add the exchanges you want to the dictionary.

d = {'A':'T','C':'G','T':'A','G':'C'}

with open("seqs.fasta", 'r') as in_file:
    for line in in_file:
        if line != '\n': # skip empty lines
            line = line.strip() # Remove new line character (I'm working on windows)
            if line.startswith('>'):
                head = line
            else:
                print head
                print ''.join(d[nuc] for nuc in line[::-1])

Output:

>homo_sapiens
CAGTACGTACGTACGTACGTACGTACGTCAGTCAGTCAGTACGTCAGTCAGTCAGTCAGTACGTACGTCATGACGTACGT
ACTGACGT
>Canis_lupus
CATGACTGCATGCATGACGTCAGTACGTCAGTACTGCAGTCATGCATGCATGCATGCATGCAGTACTGACTGACGTCATG
ACTGCATGCATGCATGACTG
>Pan_troglodytus
ATGATGCATGCATGACTGACTGCATGACTGCAGTCATGATGCATGCATGCATGCATGCATGCATGATGCATGCATGCAGT
ATGCATG
like image 137
Harpal Avatar answered Jul 24 '26 05:07

Harpal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!