pybedtools

0.12.0 · active · verified Thu Apr 16

pybedtools wraps and extends BEDTools and offers feature-level manipulations from within Python. It allows for genomic interval manipulation, also known as 'genome algebra'. The current version is 0.12.0, and it generally follows the release cadence of BEDTools, with major updates happening periodically.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create `BedTool` objects from existing BED files, perform an intersection operation (like `intersectBed`), and save the results to a new file, including adding a track line.

import pybedtools
import os

# Create dummy files for demonstration
# In a real scenario, these would be your actual genomic files
with open('snps.bed', 'w') as f:
    f.write('chr1\t10\t20\tSNP1\n')
    f.write('chr1\t30\t40\tSNP2\n')
with open('exons.bed', 'w') as f:
    f.write('chr1\t15\t25\tEXON1\n')
    f.write('chr1\t35\t45\tEXON2\n')

# Create BedTool objects from files
snps = pybedtools.BedTool('snps.bed')
exons = pybedtools.BedTool('exons.bed')

# Perform an intersection and save the results
# This example saves a new BED file of intersections
# between snps.bed and exons.bed
intersected_bed = snps.intersect(exons)
output_filename = 'snps_in_exons.bed'
intersected_bed.saveas(output_filename, trackline="track name='SNPs in exons' color=128,0,0")

print(f"Intersection results saved to {output_filename}:")
with open(output_filename, 'r') as f:
    print(f.read())

# Clean up dummy files
os.remove('snps.bed')
os.remove('exons.bed')
os.remove(output_filename)

view raw JSON →