The main function is Bio.SeqIO.parse(...) which takes an input file handle (or in recent versions of Biopython alternatively a filename as a string), and format string. This returns an iterator giving SeqRecord objects:
>>> from Bio import SeqIO >>> for record in SeqIO.parse("Fasta/f002", "fasta"): ... print("%s %i" % (record.id, len(record))) gi|1348912|gb|G26680|G26680 633 gi|1348917|gb|G26685|G26685 413 gi|1592936|gb|G29385|G29385 471
Note that the parse() function will invoke the relevant parser for the format with its default settings. You may want more control, in which case you need to create a format specific sequence iterator directly.
If you expect your file to contain one-and-only-one record, then we provide the following 'helper' function which will return a single SeqRecord, or raise an exception if there are no records or more than one record:
>>> from Bio import SeqIO >>> record = SeqIO.read("Fasta/f001", "fasta") >>> print("%s %i" % (record.id, len(record))) gi|3318709|pdb|1A91| 79
This style is useful when you expect a single record only (and would consider multiple records an error). For example, when dealing with GenBank files for bacterial genomes or chromosomes, there is normally only a single record. Alternatively, use this with a handle when downloading a single record from the internet.
However, if you just want the first record from a file containing multiple record, use the next() function on the iterator (or under Python 2, the iterator's next() method):
>>> from Bio import SeqIO >>> record = next(SeqIO.parse("Fasta/f002", "fasta")) >>> print("%s %i" % (record.id, len(record))) gi|1348912|gb|G26680|G26680 633
The above code will work as long as the file contains at least one record. Note that if there is more than one record, the remaining records will be silently ignored.
For non-interlaced files (e.g. Fasta, GenBank, EMBL) with multiple records using a sequence iterator can save you a lot of memory (RAM). There is less benefit for interlaced file formats (e.g. most multiple alignment file formats). However, an iterator only lets you access the records one by one.
If you want random access to the records by number, turn this into a list:
>>> from Bio import SeqIO >>> records = list(SeqIO.parse("Fasta/f002", "fasta")) >>> len(records) 3 >>> print(records[1].id) gi|1348917|gb|G26685|G26685
If you want random access to the records by a key such as the record id, turn the iterator into a dictionary:
>>> from Bio import SeqIO >>> record_dict = SeqIO.to_dict(SeqIO.parse("Fasta/f002", "fasta")) >>> len(record_dict) 3 >>> print(len(record_dict["gi|1348917|gb|G26685|G26685"])) 413
However, using list() or the to_dict() function will load all the records into memory at once, and therefore is not possible on very large files. Instead, for *some* file formats Bio.SeqIO provides an indexing approach providing dictionary like access to any record. For example,
>>> from Bio import SeqIO >>> record_dict = SeqIO.index("Fasta/f002", "fasta") >>> len(record_dict) 3 >>> print(len(record_dict["gi|1348917|gb|G26685|G26685"])) 413
Many but not all of the supported input file formats can be indexed like this. For example "fasta", "fastq", "qual" and even the binary format "sff" work, but alignment formats like "phylip", "clustalw" and "nexus" will not.
In most cases you can also use SeqIO.index to get the record from the file as a raw string (not a SeqRecord). This can be useful for example to extract a sub-set of records from a file where SeqIO cannot output the file format (e.g. the plain text SwissProt format, "swiss") or where it is important to keep the output 100% identical to the input). For example,
>>> from Bio import SeqIO >>> record_dict = SeqIO.index("Fasta/f002", "fasta") >>> len(record_dict) 3 >>> print(record_dict.get_raw("gi|1348917|gb|G26685|G26685").decode()) >gi|1348917|gb|G26685|G26685 human STS STS_D11734. CGGAGCCAGCGAGCATATGCTGCATGAGGACCTTTCTATCTTACATTATGGCTGGGAATCTTACTCTTTC ATCTGATACCTTGTTCAGATTTCAAAATAGTTGTAGCCTTATCCTGGTTTTACAGATGTGAAACTTTCAA GAGATTTACTGACTTTCCTAGAATAGTTTCTCTACTGGAAACCTGATGCTTTTATAAGCCATTGTGATTA GGATGACTGTTACAGGCTTAGCTTTGTGTGAAANCCAGTCACCTTTCTCCTAGGTAATGAGTAGTGCTGT TCATATTACTNTAAGTTCTATAGCATACTTGCNATCCTTTANCCATGCTTATCATANGTACCATTTGAGG AATTGNTTTGCCCTTTTGGGTTTNTTNTTGGTAAANNNTTCCCGGGTGGGGGNGGTNNNGAAA>>> print(record_dict["gi|1348917|gb|G26685|G26685"].format("fasta")) >gi|1348917|gb|G26685|G26685 human STS STS_D11734. CGGAGCCAGCGAGCATATGCTGCATGAGGACCTTTCTATCTTACATTATGGCTGGGAATC TTACTCTTTCATCTGATACCTTGTTCAGATTTCAAAATAGTTGTAGCCTTATCCTGGTTT TACAGATGTGAAACTTTCAAGAGATTTACTGACTTTCCTAGAATAGTTTCTCTACTGGAA ACCTGATGCTTTTATAAGCCATTGTGATTAGGATGACTGTTACAGGCTTAGCTTTGTGTG AAANCCAGTCACCTTTCTCCTAGGTAATGAGTAGTGCTGTTCATATTACTNTAAGTTCTA TAGCATACTTGCNATCCTTTANCCATGCTTATCATANGTACCATTTGAGGAATTGNTTTG CCCTTTTGGGTTTNTTNTTGGTAAANNNTTCCCGGGTGGGGGNGGTNNNGAAA
Here the original file and what Biopython would output differ in the line wrapping. Also note that under Python 3, the get_raw method will return a bytes string, hence the use of decode to turn it into a (unicode) string. This is uncessary on Python 2.
Also note that the get_raw method will preserve the newline endings. This example FASTQ file uses Unix style endings (b"\n" only),
>>> from Bio import SeqIO >>> fastq_dict = SeqIO.index("Quality/example.fastq", "fastq") >>> len(fastq_dict) 3 >>> raw = fastq_dict.get_raw("EAS54_6_R1_2_1_540_792") >>> raw.count(b"\n") 4 >>> raw.count(b"\r\n") 0 >>> b"\r" in raw False >>> len(raw) 78
Here is the same file but using DOS/Windows new lines (b"\r\n" instead),
>>> from Bio import SeqIO >>> fastq_dict = SeqIO.index("Quality/example_dos.fastq", "fastq") >>> len(fastq_dict) 3 >>> raw = fastq_dict.get_raw("EAS54_6_R1_2_1_540_792") >>> raw.count(b"\n") 4 >>> raw.count(b"\r\n") 4 >>> b"\r\n" in raw True >>> len(raw) 82
Because this uses two bytes for each new line, the file is longer than the Unix equivalent with only one byte.
You can read in alignment files as alignment objects using Bio.AlignIO. Alternatively, reading in an alignment file format via Bio.SeqIO will give you a SeqRecord for each row of each alignment:
>>> from Bio import SeqIO >>> for record in SeqIO.parse("Clustalw/hedgehog.aln", "clustal"): ... print("%s %i" % (record.id, len(record))) gi|167877390|gb|EDS40773.1| 447 gi|167234445|ref|NP_001107837. 447 gi|74100009|gb|AAZ99217.1| 447 gi|13990994|dbj|BAA33523.2| 447 gi|56122354|gb|AAV74328.1| 447
Use the function Bio.SeqIO.write(...), which takes a complete set of SeqRecord objects (either as a list, or an iterator), an output file handle (or in recent versions of Biopython an output filename as a string) and of course the file format:
from Bio import SeqIO records = ... SeqIO.write(records, "example.faa", "fasta")
Or, using a handle:
from Bio import SeqIO records = ... with open("example.faa", "w") as handle: SeqIO.write(records, handle, "fasta")
You are expected to call this function once (with all your records) and if using a handle, make sure you close it to flush the data to the hard disk.
The effect of calling write() multiple times on a single file will vary depending on the file format, and is best avoided unless you have a strong reason to do so.
If you give a filename, then each time you call write() the existing file will be overwriten. For sequential files formats (e.g. fasta, genbank) each "record block" holds a single sequence. For these files it would probably be safe to call write() multiple times by re-using the same handle.
However, trying this for certain alignment formats (e.g. phylip, clustal, stockholm) would have the effect of concatenating several multiple sequence alignments together. Such files are created by the PHYLIP suite of programs for bootstrap analysis, but it is clearer to do this via Bio.AlignIO instead.
The Bio.SeqIO.convert(...) function allows an easy interface for simple file format conversions. Additionally, it may use file format specific optimisations so this should be the fastest way too.
In general however, you can combine the Bio.SeqIO.parse(...) function with the Bio.SeqIO.write(...) function for sequence file conversion. Using generator expressions or generator functions provides a memory efficient way to perform filtering or other extra operations as part of the process.
When specifying the file format, use lowercase strings. The same format names are also used in Bio.AlignIO and include the following:
Note that while Bio.SeqIO can read all the above file formats, it cannot write to all of them.
You can also use any file format supported by Bio.AlignIO, such as "nexus", "phlip" and "stockholm", which gives you access to the individual sequences making up each alignment as SeqRecords.