How to append reads to a BAM file

553 views
Skip to first unread message

Waruna Ranasinghe

unread,
Nov 29, 2012, 7:49:41 PM11/29/12
to pysam-us...@googlegroups.com
Hi all,

I have two BAM files, I need to append some of the reads of one BAM file to the other BAM file.
But, after I write the reads, then the appended BAM file only have the newly appended reads. All the old reads are gone.

I use the following piece of code.

target_bam_file = pysam.Samfile("mybamfile.bam", "wb", template=source_bam_file)
target_bam_file.write(read)

Can someone let me know how to append reads to a BAM file?

Do I need to seek the end of file and then start append the reads? If so do you know how to find the end of BAM file.

Thanks and regards,
Waruna

Abhishek Pratap

unread,
Nov 29, 2012, 7:59:36 PM11/29/12
to pysam-us...@googlegroups.com
I haven't tried it but may be this works. Instead of "w"use "a"
> target_bam_file = pysam.Samfile("mybamfile.bam", "ab",template=source_bam_file)

hth,
-Abhi

Waruna Ranasinghe

unread,
Nov 29, 2012, 8:06:12 PM11/29/12
to pysam-us...@googlegroups.com
Hi Abhi,

I just tried it but throws the following exception. It seems "a" is invalid

 target_bam_file = pysam.Samfile(target_improved_sam_file_directory + target_bam_file_name + ".bam", "ab", template=source_bam_file)
  File "csamtools.pyx", line 463, in csamtools.Samfile.__cinit__ (pysam/csamtools.c:4758)
  File "csamtools.pyx", line 510, in csamtools.Samfile._open (pysam/csamtools.c:5457)
AssertionError: invalid file opening mode `ab`

Peter Cock

unread,
Nov 30, 2012, 6:29:31 AM11/30/12
to pysam-us...@googlegroups.com
In theory that could work, but I don't know how easy it would be with
the pysam API. One critical issue is the list of references must match
between the two BAM files if you hope to transfer entries from one
to the other (when mapped to a reference the reference is stored
as an integer citing the reference list). If not, you may have to
update the reference numbers.

I think the simplest solution is to output two BAM files and
call 'samtools merge' to do the hard work.

Peter
Reply all
Reply to author
Forward
0 new messages