Input
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.
Input - Single Records
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.
Input - Multiple Records
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 <BLANKLINE> >>> 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 <BLANKLINE>
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.
Input - Alignments
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
Output
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.
Output - Advanced
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.
Conversion
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.
File Formats
When specifying the file format, use lowercase strings. The same format names are also used in Bio.AlignIO and include the following:
- abif - Applied Biosystem's sequencing trace format
- ace - Reads the contig sequences from an ACE assembly file.
- embl - The EMBL flat file format. Uses Bio.GenBank internally.
- fasta - The generic sequence file format where each record starts with an identifer line starting with a ">" character, followed by lines of sequence.
- fastq - A "FASTA like" format used by Sanger which also stores PHRED sequence quality values (with an ASCII offset of 33).
- fastq-sanger - An alias for "fastq" for consistency with BioPerl and EMBOSS
- fastq-solexa - Original Solexa/Illumnia variant of the FASTQ format which encodes Solexa quality scores (not PHRED quality scores) with an ASCII offset of 64.
- fastq-illumina - Solexa/Illumina 1.3 to 1.7 variant of the FASTQ format which encodes PHRED quality scores with an ASCII offset of 64 (not 33). Note as of version 1.8 of the CASAVA pipeline Illumina will produce FASTQ files using the standard Sanger encoding.
- genbank - The GenBank or GenPept flat file format.
- gb - An alias for "genbank", for consistency with NCBI Entrez Utilities
- ig - The IntelliGenetics file format, apparently the same as the MASE alignment format.
- imgt - An EMBL like format from IMGT where the feature tables are more indented to allow for longer feature types.
- phd - Output from PHRED, used by PHRAP and CONSED for input.
- pir - A "FASTA like" format introduced by the National Biomedical Research Foundation (NBRF) for the Protein Information Resource (PIR) database, now part of UniProt.
- seqxml - SeqXML, simple XML format described in Schmitt et al (2011).
- sff - Standard Flowgram Format (SFF), typical output from Roche 454.
- sff-trim - Standard Flowgram Format (SFF) with given trimming applied.
- swiss - Plain text Swiss-Prot aka UniProt format.
- tab - Simple two column tab separated sequence files, where each line holds a record's identifier and sequence. For example, this is used as by Aligent's eArray software when saving microarray probes in a minimal tab delimited text file.
- qual - A "FASTA like" format holding PHRED quality values from sequencing DNA, but no actual sequences (usually provided in separate FASTA files).
- uniprot-xml - The UniProt XML format (replacement for the SwissProt plain text format which we call "swiss")
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.