1
$\begingroup$

I have this code to filter some IDs from a fasta file:

for line in file_open:
    line=line.rstrip()
    if '16S' in line:
        header=line
        header=header[0] + header[1:]
        seq=file_open.readline()
        seq=seq.strip()
        print(header + '\n'  + seq)

however, this code doesn't get me all content of each ID sequence. I get this result:

>ID1
AGTTTTGCCGAATTCCTTTAGGATTTTGTGAGGAACATTGTGTTAAATGTATTTATAGTTCTACTAATTC

When I should get this:

>ID1
AGTTTTGCCGAATTCCTTTAGGATTTTGTGAGGAACATTGTGTTAAATGTATTTATAGTTCTACTAATTC
TGCGAAGGTAGCATAATCATTAGCCTTTTGATTTGAGGCTGGAATGAATGGTTTGACGAGAGATGGTCTG
GGGCCGTGGTATACTGACCATGCGAAGGTAGCATAATCATTAGCCTCTTGATTTGAGGCTGGAATGAATG
GGGCCGTGGTATAC

Thanks

$\endgroup$
5
  • 4
    $\begingroup$ Does this answer your question? Remove/delete sequences by ID from multifasta $\endgroup$ – Konrad Rudolph Sep 24 '20 at 15:27
  • $\begingroup$ Well, the code you wrote prints the seq on a single line (and without any newline afterwards), are you sure that's not the only problem? $\endgroup$ – Kamil S Jaron Sep 26 '20 at 19:25
  • $\begingroup$ @KonradRudolph I think the question is more about writing the fasta file well formated. $\endgroup$ – Kamil S Jaron Sep 26 '20 at 19:25
  • 1
    $\begingroup$ @KamilSJaron No, the question isn’t about formatting. Check the output in the question again. It isn’t all on one line, it’s truncated (as in, only the first line is read and written, subsequent lines are omitted). $\endgroup$ – Konrad Rudolph Sep 28 '20 at 8:07
  • $\begingroup$ I thought that the truncated line could be due to copypasting. Now I see, it's not about the formatting of output, but expected formatting of the input. $\endgroup$ – Kamil S Jaron Sep 28 '20 at 9:06
8
$\begingroup$

You're assuming 2-line FASTA format, but the sequence can (and typically does) span multiple lines. You can use Biopython to build a simple parser:

from Bio import SeqIO

for record in SeqIO.parse("file_name.fa", "fasta"):
    if "16S" in record.description:
        print(record.format("fasta"))
$\endgroup$
1
  • $\begingroup$ This was really helpful, thank you so much $\endgroup$ – Sofia Oct 16 '19 at 9:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.