forked from bmajoros/python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFastaWriter.py
executable file
·54 lines (48 loc) · 1.96 KB
/
FastaWriter.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#=========================================================================
# This is OPEN SOURCE SOFTWARE governed by the Gnu General Public
# License (GPL) version 3, as described at www.opensource.org.
# Copyright (C)2016 William H. Majoros ([email protected]).
#=========================================================================
from __future__ import (absolute_import, division, print_function,
unicode_literals, generators, nested_scopes, with_statement)
from builtins import (bytes, dict, int, list, object, range, str, ascii,
chr, hex, input, next, oct, open, pow, round, super, filter, map, zip)
import re
import os
#=========================================================================
# Attributes:
# width
# Methods:
# FastaWriter()
# Instance Methods:
# writer=FastaWriter(optionalWidth)
# writer.writeFasta(defline,sequence,filename)
# writer.appendToFasta(defline,sequence,filename)
# writer.addToFasta(defline,sequence,filehandle)
#=========================================================================
class FastaWriter:
"""FastaWriter"""
def __init__(self,width=60):
self.width=width
def writeFasta(self,defline,seq,filename):
with open(filename,"w") as fh:
self.addToFasta(defline,seq,fh)
def addToFasta(self,defline,seq,fh):
defline=defline.rstrip()
if(not re.search("^\s*>",defline)): defline=">"+defline
fh.write(defline+"\n");
length=len(seq)
numLines=length//self.width
if(length%self.width>0): numLines+=1
start=0
for i in range(0,numLines):
line=seq[start:start+self.width]
fh.write(line+"\n")
start+=self.width
if(length==0): fh.write("\n")
def appendToFasta(self,defline,seq,filename):
if(not os.path.exists(filename)):
self.writeFasta(defline,seq,filename)
return
with open(filename,"a") as fh:
self.addToFasta(defline,seq,fh)