bioinformatics Common File Formats Sequence Writing In fasta Format


Example

This a python example function for sequence writing in fasta format.

Parameters:

  • filename(String) - A file name for writing sequence in fasta format.
  • seq(String) - A DNA or RNA sequence.
  • id(String) - The ID of the given sequence.
  • desc(String) - A short description of the given sequence.
import math

    def save_fsta(filename,seq,id,desc):
        fo = open(filename+'.fa',"a")
        header= str(id)+' <'+desc+'> \n'
        fo.write(header)
        count=math.floor(len(seq)/80+1)
        iteration = range(count)
        for i in iteration:
            fo.write(seq[80*(i):80*(i+1)]+'\n')        
        fo.write('\n \n')
        fo.close()

Another way is using textwrap

import textwrap

def save_fasta(filename,seq, id, desc):
    filename+='.fa'
    with open(filename, 'w') as f:
        f.write('>'+id+' <'+desc+'>\n');
        text = textwrap.wrap(seq,80);
        for x in text:
            f.write(x+'\n');