This is a test version of Biostars. For the public version, visit https://www.biostars.org.
Filter BAM by chromosome using PySam

Hi all!

I am trying to filter a BAM by chromosome using PySam.

Using Samtools:

samtools view -h mybam.bam 22 > mybam.bam.chr22.sam
samtools view -bS mybam.bam.chr22.sam > mybam.bam.chr22.bam

Using PySam:

filtered_sam = pysam.view("-h", bam_path, chromosome) # This is returning a simple string instead of a PySam object
return pysam.view("-bS", filtered_sam) # This doesn't seem to work

What I want is to read the BAM, filter it out by chromosome but not saving the extra .sam/.bam files. Just read it, filter and the loop thought it by using:

for read in filtered_bam:
    ....

I also tried this without succeed:

pysam.AlignmentFile(pysam.view(bam_path, chromosome, '-b'))
...
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 1: invalid start byte

What I am doing wrong? Thank you very much!

pysam bam python samtools

0 answers

No answers yet.

Log in to answer this question.