This is a test version of Biostars. For the public version, visit https://www.biostars.org.
Fasta Sliding Window

Hello

I am trying to find specific sequences sequences from a FASTA file and write them to a text file In a 'sliding window' fashion using biopython.

This is what I have so far:

from Bio import SeqIO

input_file = open('sequences.fasta', 'r')
output_file = open('output.fasta', 'a')

def chunks(seq, win, step):
    seqlen = len(seq)
    for i in range(0,seqlen,step):
        j = seqlen if i+win>seqlen else i+win
        yield seq[i:j]
        if j==seqlen: break

for gene in SeqIO.parse(input_file, "fasta"):
    seq = gene.seq
    for subseq in chunks(seq,150,1):
        if 'desired sequence' in gene.description:
            print(gene.description)
            print(subseq)

output_file.close()
input_file.close()

This seems to work fine using the 'print' command but my code fails when I try to write to a file by replacing the 'print' commands for:

        SeqIO.write(gene.description, output_file, "fasta")
        SeqIO.write(subseq, output_file, "fasta")

I am new to coding/python and would appreciate if anyone could help me out with this.

Thanks

python sequence fasta write biopython

Just a note: you should add a 'biopython' tag as well

1 answer

Please go to Fasta Sliding Window Post and try to find your query.

Thank you, I used that post to work out how to do the sliding window. But at the moment it is not the sliding window which is giving me trouble but the fact that I can't write it to a file.

Log in to answer this question.