\begin{Verbatim}[commandchars=\\\{\}]
\PYG{k+kn}{from} \PYG{n+nn}{Bio.SeqIO.FastaIO} \PYG{k+kn}{import} \PYG{n}{SimpleFastaParser}
\PYG{k+kn}{from} \PYG{n+nn}{Bio} \PYG{k+kn}{import} \PYG{n}{SeqIO}

\PYG{c+c1}{\PYGZsh{} Get the lengths and ids, and sort on length}
\PYG{k}{with} \PYG{n+nb}{open}\PYG{p}{(}\PYG{l+s+s2}{\PYGZdq{}ls\PYGZus{}orchid.fasta\PYGZdq{}}\PYG{p}{)} \PYG{k}{as} \PYG{n}{in\PYGZus{}handle}\PYG{p}{:}
    \PYG{n}{len\PYGZus{}and\PYGZus{}ids} \PYG{o}{=} \PYG{n+nb}{sorted}\PYG{p}{(}
        \PYG{p}{(}\PYG{n+nb}{len}\PYG{p}{(}\PYG{n}{seq}\PYG{p}{),} \PYG{n}{title}\PYG{o}{.}\PYG{n}{split}\PYG{p}{(}\PYG{k+kc}{None}\PYG{p}{,} \PYG{l+m+mi}{1}\PYG{p}{)[}\PYG{l+m+mi}{0}\PYG{p}{])}
        \PYG{k}{for} \PYG{n}{title}\PYG{p}{,} \PYG{n}{seq} \PYG{o+ow}{in} \PYG{n}{SimpleFastaParser}\PYG{p}{(}\PYG{n}{in\PYGZus{}handle}\PYG{p}{)}
    \PYG{p}{)}
\PYG{n}{ids} \PYG{o}{=} \PYG{n+nb}{reversed}\PYG{p}{([}\PYG{n+nb}{id} \PYG{k}{for} \PYG{p}{(}\PYG{n}{length}\PYG{p}{,} \PYG{n+nb}{id}\PYG{p}{)} \PYG{o+ow}{in} \PYG{n}{len\PYGZus{}and\PYGZus{}ids}\PYG{p}{])}
\PYG{k}{del} \PYG{n}{len\PYGZus{}and\PYGZus{}ids}  \PYG{c+c1}{\PYGZsh{} free this memory}

\PYG{n}{record\PYGZus{}index} \PYG{o}{=} \PYG{n}{SeqIO}\PYG{o}{.}\PYG{n}{index}\PYG{p}{(}\PYG{l+s+s2}{\PYGZdq{}ls\PYGZus{}orchid.fasta\PYGZdq{}}\PYG{p}{,} \PYG{l+s+s2}{\PYGZdq{}fasta\PYGZdq{}}\PYG{p}{)}
\PYG{k}{with} \PYG{n+nb}{open}\PYG{p}{(}\PYG{l+s+s2}{\PYGZdq{}sorted.fasta\PYGZdq{}}\PYG{p}{,} \PYG{l+s+s2}{\PYGZdq{}wb\PYGZdq{}}\PYG{p}{)} \PYG{k}{as} \PYG{n}{out\PYGZus{}handle}\PYG{p}{:}
    \PYG{k}{for} \PYG{n+nb}{id} \PYG{o+ow}{in} \PYG{n}{ids}\PYG{p}{:}
        \PYG{n}{out\PYGZus{}handle}\PYG{o}{.}\PYG{n}{write}\PYG{p}{(}\PYG{n}{record\PYGZus{}index}\PYG{o}{.}\PYG{n}{get\PYGZus{}raw}\PYG{p}{(}\PYG{n+nb}{id}\PYG{p}{))}
\end{Verbatim}
