Change DNA sequences in fasta file using Biopython
<p>I have a file in fasta format with several DNA sequences. I want to change the content of each sequence for another smaller sequence, keeping the same sequence id.
The new sequences are in a list.</p>

<pre><code>with open("outfile.fa", "w") as f:
    for seq_record in SeqIO.parse("ma-all-mito.fa", "fasta"):
        for i in range(len(newSequences_ok)):
            f.write(str(seq_record.id[i]) + "\n")
            f.write(str(newSequences_ok[i]) + "\n")  
</code></pre>

<p>But I get:</p>

<pre><code>IndexError: string index out of range
</code></pre>

<p>How could I change the code so that it works? I think the problem is that I need to iterate both through the original fasta file and through the list with the new sequences.</p>

<p>The original fasta file looks like this:</p>

<pre><code>&gt;Sequence1
ATGATGCATGG
&gt;Sequence2
TTTTGGGAATC
&gt;Sequence3
GGGCTAACTAC
&gt;Sequence4
ATCTCAGGAA
</code></pre>

<p>And the list with the new sequences is similar to this one:</p>

<pre><code>newSequences_ok=[ATGG,TTTC,GGTA,CTCG]
</code></pre>

<p>The output that I would like to get is:</p>

<pre><code>&gt;Sequence1
ATGG
&gt;Sequence2
TTTC
&gt;Sequence3
GGTA
&gt;Sequence4
CTCG
</code></pre>

<p>I think that this <em>might</em> work:</p>

<pre><code>records = SeqIO.parse("ma-all-mito.fa", "fasta")
with open("outfile.fa", "w") as f:
    for r, s in zip(records,newSequences_ok):
        f.write(r.seq.seq.split('\n')[0] + '\n')
        f.write(s + '\n')
</code></pre>

<p>If not (and even if it does) -- you really need to read up on how <a href="http://biopython.org/DIST/docs/tutorial/Tutorial.html#htoc32" rel="nofollow">Biopython</a> works. You were treating <code>SeqIO.parse</code> as something which directly returns the lines of the files. Instead, it returns <code>SeqRecord</code> objects which have a <code>seq</code> attribute which returns <code>Seq</code> objects which themselves have two attributes, a <code>seq</code> attribute (which is what you seem to want) and an <code>alphabet</code> attribute. You should concentrate on being able to extract the information that you are interested in before you try to modify it.</p>

python biopython fasta