pyfaidx is a Python library that provides efficient, pythonic random access to subsequences within FASTA files, compatible with samtools index format (.fai). It allows for fast retrieval and in-place modification without loading the entire file into memory. The current version is 0.9.0.4, with frequent minor updates and bug fixes.
pip install pyfaidxVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to initialize a `Fasta` object, access sequences by their header names, retrieve subsequences using slicing, and perform operations like reverse complementation. It also highlights the default 1-based indexing for sequence attributes, while slicing remains 0-based Pythonic.
Upgrade to pyfaidx version 0.9.0.3 or higher (`pip install --upgrade pyfaidx`).
Be mindful of the coordinate system. For Pythonic 0-based slicing, use `fasta_obj['name'][0_based_start:0_based_end]`. If you need to work with 1-based coordinates for display or interoperability with tools like samtools, remember to adjust your slice indices accordingly (e.g., 1-based `start` corresponds to 0-based `start - 1`).
Ensure your FASTA files are properly formatted with consistent line lengths. Tools like `seqtk` or `bbtools reformat` can help standardize FASTA formats if you encounter this issue.
Initialize `Fasta('your.fasta', read_long_names=True)` if full FASTA headers are required. For compressed files, consider decompressing or processing headers separately if full names are critical.Ensure that all sequence lines for a given entry in your FASTA file (excluding the header line) have the same length. Tools like `seqtk` or custom scripts can often reformat FASTA files to fix this issue.
When initializing `Fasta` or `Faidx`, use `read_long_names=True` to instruct `pyfaidx` to use the entire FASTA header line as the key, thereby avoiding unintended duplicates from whitespace splitting. Alternatively, ensure your FASTA headers are unique after splitting on whitespace. Example: `genes = Fasta('your.fasta', read_long_names=True)`Install the `pyfaidx` library using pip: `pip install pyfaidx`. If you are working in a virtual environment, ensure it is activated before installation.
Adjust the `start` and `end` coordinates to ensure that `start` is strictly less than `end` (e.g., `start=1, end=10` is valid, `start=10, end=10` is invalid for a positive length). If you need to handle zero-length queries or want less strict bounds checking, initialize your `Fasta` or `Faidx` object with `strict_bounds=False`. Example: `genes = Fasta('your.fasta', strict_bounds=False)`