This is a test version of Biostars. For the public version, visit https://www.biostars.org.
How to merge set of bam files into one?

is there a pythonic way to merge a set of bam files?

merge bam python pysam

Why does it need to be pythonic? There are far more straightforward command line ways to do this.

Thanks Ram. I am aware of the straightforward ways. I am just curious if I can do this with python.

Got it. We've seen a lot of users that pick tech first, task later so this sort of awareness is not always present. Glad you figured out a solution, it always helps understand the underlying challenges.

1 answer

I figured out the answer to this one. I am writing down it here for future me and all other curious people.

import pysam

list_of_bamfiles = [f.bam,f2.bam]

pysam.merge("-f","-o","output.bam",*list_of_bamfile)
# the * before the list unpack the list of arguments

Thanks for sharing this! What do the first two arguments ("-f","-o") stand for?

Please read the manual: https://pysam.readthedocs.io/en/latest/usage.html#using-samtools-commands-within-python

Commands available in samtools are available as simple function calls. Command line options are provided as arguments. For example:

pysam.sort("-o", "output.bam", "ex1.bam")

corresponds to the command line:

samtools sort -o output.bam ex1.bam

Then lookup the samtools merge manual page: https://www.htslib.org/doc/samtools-merge.html to see what -f and -o mean.

Log in to answer this question.