I would like to convert my SAM file to a BAM using pysam library. I am trying to write this command from samtools:
samtools view -S -b sample.sam > sample.bam
as a python code like this:
pysam.view("-S", "-b", "sample.sam", ">", "sample.bam")
according to this documentation. But unfortunately it doesn't work. How can I do it? Should I create an empty BAM file before or will it be created automatically? In the end I have this error:
SamtoolsError: 'samtools returned with error 1: stdout=b'\x1f\x8b\x08\x04\x00\x00\x00\x00\x00\xff\x06\x00BC\x02\x004\x01\x9dQMO\x83@\x10\xa5G\xfa#\xccz\xb3\x87\xfd\xa2\xa0\x86\x83\xa9\xad\xd86i\t\x16\xc3u\xb3P\xc0&,PvcC\xff\xa6\x7f\xc8\xc5\x88&\xe8\xc1xx\x99\xc9\xbcyy\x937\xf3\xfb\xed\xe8md\x18\xb3\xf0\xc9\x0c}\xd7"\x90\x90)a\xa1\xc5\xe8.\xcdX\xd2&\x8cPv\xb9\xf2"\xb8\x8av\xac\xac\xd6\xa5L\x1ben\xf4\xee\xed\xf5x\x16,\xcd\xf5\x83\x1b\x9f\xb8\x19\xf8\x1f%\xf2]\x82n\x10u`C\xa9M\xcc\xc5\xa6\x1b\x03\x91\n\x00\x95E\x00\x9c[\x00>;\x00\xcb\xa4\xe1*y\xc1\xbcP\x82\x97e\x8c\xfde\xc8\x1e\x97\xd4\xc1\xbd\x99\x97W\r\x1e\\\x84\x89\xcd\x9a\x94\xef%\x13\xbc\xae\xd3=\xde\xf2z\xd1&\x84~5l\xa0@\x19\x97\x8a\xff\xdfo\xfa\xe9\x97\x1dJ^\x0ci\x16z(;\xa2\xfc\xdc\'!\xb9PUU\xc8.\x8e\xef>\xe8\xa3\xa1\x88\x12pU\xb7\x9a\x9at\xd1\xf4+\xe0\xf5\x90\x9e\x00\x0c\x01\x8c\x01\xac\x00V\xa2\xee\x10g\xb6<\xe6\x9a\xfei\x1bxH\x8b\xc1\xdd\xefT\xcc\xc5X\x7f\xd5\x98h\xfc\xf5\xa7\xc6\x85V\xbc\x03\xb7nn4\x10\x02\x00\x00\x1f\x8b\x08\x04\x00\x00\x00\x00\x00\xff\x06\x00BC\x02\x00\x1b\x00\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00', stderr=[main_samview] random alignment retrieval only works for indexed BAM or CRAM files.\n'
Thank you in advance!
You can use
pysam.sort
function to convert SAM to BAM.