Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Free lesson

Reading a FASTA file in Python

After this lesson: I can read the sequences in a FASTA file into a dictionary.

55 min lesson2 commandsJupyterLab data science lab: pandas, Matplotlib and scikit-learn in the browser

A FASTA file stores sequences as plain text

A FASTA file is a plain text file that stores one or more biological sequences. Each sequence starts with a header line that begins with the symbol >, and the bases follow.

Almost every sequence tool starts by reading FASTA, so this is the first job to learn. You will turn the text into names and sequences a program can use.

By the end of this lesson

Note

I can read the sequences in a FASTA file into a dictionary.

Key words

WordWhat it meansExample
FASTAa text format for sequences
Headerthe line that names a sequence>seq1 invented sample A
Recordone header and its sequence
Wrapped lineone part of a sequence split over several lines
Identifierthe first word of a header

The cells students fill in are left blank in this preview.

A record is a header and its sequence

A FASTA file is made of records. A record begins with a header, a line starting with >. Everything after the symbol names the sequence, such as seq1 invented sample A.

The sequence lines follow, up to the next header or the end of the file. The first word of the header is the identifier.

Tell header lines from sequence lines

Code: python
text = """>seq1 invented sample A
ATGGCGC
ATTAGCC
>seq2 invented sample B
GGATCC
"""
for line in text.split("\n"):
    if line.startswith(">"):
        print("header:", line)
    elif line != "":
        print("bases: ", line, len(line))
# Add a third record of your own at the end of the text, then run again.

Long sequences are wrapped over several lines

Sequence lines are kept short so the file stays easy to read. A sequence of 150 bases may sit on three lines of 60, 60 and 30.

The line breaks are not part of the sequence. To rebuild it, join the lines of one record with nothing between them.

Worked example: what to do with each line

LineKindWhat the program does
>seq1 invented sample AHeaderStart a new record named seq1
ATGGCGCSequence lineAdd 7 bases to seq1
ATTAGCCSequence lineAdd 7 more, so seq1 has 14
>seq2 invented sample BHeaderStart a new record named seq2
GGATCCSequence lineAdd 6 bases to seq2
(empty)Blank lineSkip it

The cells students fill in are left blank in this preview.

Join the lines of each record

Code: python
text = """>seq1 invented sample A
ATGGCGC
ATTAGCC
>seq2 invented sample B
GGATCC
"""
records = {}
name = ""
for line in text.split("\n"):
    line = line.strip()
    if line.startswith(">"):
        name = line[1:].split(" ")[0]
        records[name] = ""
    elif line != "":
        records[name] = records[name] + line
for name in records:
    print(name, len(records[name]), records[name])
# Make the first record wrap onto a third line and check the length.

A common mistake

Warning

Many people think each line of a FASTA file is a separate sequence. Only a line that starts with > begins a record. The lines after it belong to the same sequence until the next header appears.

Count the headers in a small FASTA text

Command
docker exec jupyter python3 -c "t = '>a first\nACGT\nAC\n>b\nGG\n'; print(t.count('>'))"

Shown here, not run. Create a free account to press Run and type it into your own lab’s terminal.

Count the bases on the sequence lines

Command
docker exec jupyter python3 -c "t = '>a first\nACGT\nAC\n>b\nGG\n'; print(sum(len(l) for l in t.split('\n') if not l.startswith('>')))"

Shown here, not run. Create a free account to press Run and type it into your own lab’s terminal.

The two commands print 2 and then 8

The text holds two records, so the first command prints 2. It counts the symbol >.

The second command adds up the lengths of every line that is not a header: 4, 2 and 2. It prints 8, the total number of bases in both records.

About this lab and its source: JupyterLab data science lab: pandas, Matplotlib and scikit-learn in the browser

Teaching a class? Set this module for your students with a teacher guide, marked assignments and a lab for every student.