Registry / data / pysam
library0.24.0pypypi✓ verified 26d ago

Pysam is a Python module for reading, manipulating, and writing genomic datasets. It is a lightweight wrapper of the HTSlib API, providing facilities to work with SAM/BAM/CRAM, VCF/BCF, BED, GFF/GTF, FASTA/FASTQ files, and access samtools/bcftools command-line functionality. The module supports compression and random access through indexing. Pysam is actively maintained with regular releases, often wrapping new versions of the underlying htslib, samtools, and bcftools C libraries.

pip install pysam
INSTALL
IMPORT
SIG · PYSAM
P
pysam
datapythonv0.24.0
Install
2.4s avg
Import
71ms
Disk
94MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v0.24.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 0.068s · 76MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 2.4s · import 0.074s · 90MB
94MB installed
● package 94MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

pysam
import pysam
AlignmentFile
from pysam import AlignmentFile
import pysam.AlignmentFile
Classes like AlignmentFile, VariantFile, and FastaFile are top-level members of the pysam module.
VariantFile
from pysam import VariantFile
FastaFile
from pysam import FastaFile

This quickstart demonstrates how to open and read data from common genomic file formats (SAM, VCF, FASTA) using `pysam.AlignmentFile`, `pysam.VariantFile`, and `pysam.FastaFile`. It includes creating dummy files for a self-contained example.

import pysam import os # --- Example 1: Read a BAM/SAM file --- # Create a dummy BAM file for demonstration # In a real scenario, you would use an existing BAM file and its index. # For this quickstart, we'll create a simple unmapped SAM file first. # NOTE: pysam.AlignmentFile requires a header for 'wb' mode. header = { 'HD': {'VN': '1.0'}, 'SQ': [{'LN': 1000, 'SN': 'chr1'}] } dummy_sam_path = "example_reads.sam" with pysam.AlignmentFile(dummy_sam_path, "wh", header=header) as outfile: # Create a simple unmapped read (no reference_id or pos) read = pysam.AlignedSegment(header) read.query_name = "read1" read.query_sequence = "ATGCATGC" read.query_qualities = pysam.qualities_to_ints("BBBBBBBB") read.flag = 4 # UNMAPPED outfile.write(read) print(f"Reading from {dummy_sam_path}:") with pysam.AlignmentFile(dummy_sam_path, "r") as samfile: for read in samfile.fetch(until_eof=True): # fetch(until_eof=True) for unindexed or SAM files print(f" Read: {read.query_name}, Sequence: {read.query_sequence}, Mapped: {not read.is_unmapped}") os.remove(dummy_sam_path) # --- Example 2: Read a VCF file --- # Create a dummy VCF file dummy_vcf_path = "example_variants.vcf" with open(dummy_vcf_path, "w") as f: f.write("##fileformat=VCFv4.2\n") f.write("##contig=<ID=chr1,length=1000>\n") f.write("#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\tSAMPLE1\n") f.write("chr1\t100\t.\tA\tG\t100\tPASS\t.\tGT\t0/1\n") f.write("chr1\t200\t.\tC\tT\t90\tPASS\t.\tGT\t1/1\n") print(f"\nReading from {dummy_vcf_path}:") vcf_file = pysam.VariantFile(dummy_vcf_path, "r") for variant in vcf_file: print(f" Variant: {variant.chrom}:{variant.pos} {variant.ref}>{variant.alts}") vcf_file.close() os.remove(dummy_vcf_path) # --- Example 3: Read a FASTA file --- # Create a dummy FASTA file dummy_fasta_path = "example_reference.fasta" with open(dummy_fasta_path, "w") as f: f.write(">chr1\n") f.write("ATGCATGCATGCATGCATGCATGCATGCATGCATGCATGC\n") f.write(">chr2\n") f.write("GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG\n") print(f"\nReading from {dummy_fasta_path}:") fasta_file = pysam.FastaFile(dummy_fasta_path) sequence = fasta_file.fetch("chr1", 5, 15) # 0-based start, 0-based exclusive end print(f" Fetched sequence from chr1 (5-15): {sequence}") fasta_file.close() os.remove(dummy_fasta_path)
Debug
Known issues
breakingPysam v0.23.0 was the last release to officially support Python 3.6 and 3.7. Subsequent versions (v0.23.1 and later) require Python 3.8 or newer.
fix
Upgrade to Python 3.8 or newer, or pin pysam to a version <=0.23.0.
affects: >=0.23.1
breakingPysam v0.20.0 was the final release to support Python 2.x. All versions after 0.20.0 are Python 3-only.
fix
Migrate your project to Python 3.x and update pysam to a compatible version.
affects: >0.20.0
gotchaWhen using `AlignmentFile.fetch()` or similar methods, coordinates are generally 0-based and half-open (exclusive end). This is a common convention in bioinformatics but can lead to off-by-one errors if 1-based or fully-inclusive ranges are expected.
fix
Always confirm the coordinate system (0-based/1-based, inclusive/exclusive) for specific `pysam` functions and adjust input ranges accordingly.
affects: All versions
gotchaPysam v0.23.1 inadvertently broke binary compatibility for Cython projects that depend on pysam. This was fixed in v0.23.2. Pure Python projects using pysam were not affected.
fix
Cython projects that compiled against pysam v0.23.1 should update to v0.23.2 or later to restore binary compatibility.
affects: 0.23.1
gotchaWhile `pip install pysam` typically works by installing pre-built wheels (which include compiled htslib and do not require Cython), installing from source or a repository clone requires a C compiler and Cython to be pre-installed.
fix
Ensure a C compiler (e.g., GCC) and `cython` (`pip install cython`) are available in your environment before attempting a source installation.
affects: All versions (when installing from source)
Errors
Common errors & fixes
ValueError: file has no index
You are attempting to fetch data from a specific coordinate region in a SAM/BAM/CRAM file, which requires an index, but the file is not indexed or its index file (`.bai`, `.csi`, `.crai`) is missing or inaccessible.
fix
Index the file using `pysam.index()` or the `samtools index` command before attempting to fetch regions. Example: `pysam.index('alignment.bam')` or `samtools index alignment.bam`.
ValueError: reference 'chrM' not found in header
The specified reference sequence (e.g., 'chrM') for fetching or iterating over reads does not exist in the SAM/BAM/CRAM file's header, or its name is misspelled.
fix
Inspect the file's header to find the exact names of the available reference sequences using `samfile.references` or `samfile.fetch(until_eof=True)` to see header details, then use one of the correct names.
ImportError: cannot import name '_HTSFile' from 'pysam.libchtslib'
Pysam's C extensions (which wrap HTSlib) failed to compile or link correctly during installation, often due to missing underlying system libraries (like zlib, bzip2, xz) or compiler issues.
fix
Ensure all required system development libraries (e.g., `zlib-devel`, `libbz2-dev`, `liblzma-dev`, `libncurses-dev` on Linux, or corresponding packages on other OSes) are installed, then reinstall pysam (e.g., `pip install --force-reinstall pysam`).
OSError: cannot open file 'non_existent_file.bam': No such file or directory
Pysam could not open the specified genomic file because the file does not exist at the given path, the path is incorrect, or the program lacks the necessary read permissions for the file or its directory.
fix
Verify that the file path is correct and absolute or relative to the script's execution directory. Ensure the file exists and that you have read permissions for the file and its containing directory.
Upgrade
Version history
0.24.0latest on PyPI · released Apr 27, 2026
Audit
Dependencies
htslibrequiredCore C library wrapped by pysam for genomic file manipulation.
samtoolsrequiredProvides command-line functionality wrapped by pysam.
bcftoolsrequiredProvides command-line functionality for VCF/BCF files wrapped by pysam.
CythonoptionalRequired for installing pysam from source code or repository, but not typically needed when installing from pre-built wheels via pip.
Agent activity
14 hits · last 30 days
node
12
Resources
pysam — pip install pysam · libregistry