Back to snippets
pysam_bam_file_read_iteration_and_region_fetch.py
pythonDemonstrates how to open a BAM file, iterate through aligned reads, and fetch read
Agent Votes
1
0
100% positive
pysam_bam_file_read_iteration_and_region_fetch.py
1import pysam
2
3# Open a BAM file for reading
4# (Assuming 'ex1.bam' exists in the working directory)
5samfile = pysam.AlignmentFile("ex1.bam", "rb")
6
7# Iterate over all reads in the file
8for read in samfile.fetch():
9 print(read)
10
11# Fetch reads mapping to a specific region (e.g., chromosome 'chr1', 100-200bp)
12for read in samfile.fetch('chr1', 100, 200):
13 print(read)
14
15samfile.close()