Read a FASTA file
FASTA stores one or more records. Each begins with a header line starting with >; following lines contain the sequence until the next header.
>sequence_1 description ATGGCT TAA >sequence_2 ACGTAC
The bundled read_fasta function returns pairs of identifier and sequence. It joins wrapped lines, validates bases and detects a missing header, empty record or duplicate identifier.
from pathlib import Path
from bioinfo_practice import read_fasta, gc_percent, translate
fasta = Path("example.fasta")
for name, dna in read_fasta(fasta):
print(name, len(dna), gc_percent(dna), translate(dna))Run the complete example from the downloads folder with python bioinfo_practice.py. Then run its checks with python -m unittest -v. The test file demonstrates simple automated checks for expected behavior and invalid input.
FASTA practical
- Read
example.fastaand print each ID and length. - Add a GC% column to your output.
- Make a temporary copy with a duplicate identifier or an
Nand confirm the parser returns a readable error.
Worked answer
The supplied file contains reference and variant, both 36 bases. The parser intentionally accepts only A/C/G/T for this exercise; ambiguous symbols trigger a clear ValueError. An advanced workflow should choose an explicit ambiguity policy rather than strip symbols without explanation.