0

I am trying to write a python script that loops through SAM files in a directory and uses samtools view to convert those SAM files to BAM files. Here's what I have, but am struggling with how to input the SAM file (i) into the bash command in the last line.

import os
import glob
for i in glob.iglob('/file/path/to/files/*.sam'):
      os.system("samtools view -S -b %i > %i.bam" %i)

Thank you for your help!

oguz ismail
  • 1
  • 16
  • 47
  • 69
Emerson
  • 125
  • 8

2 Answers2

3

With up-to-date Python version you can use f-strings where f stands for formatting.

os.system(f"samtools view -S -b {i} > {i}.bam")
Mikko Ohtamaa
  • 82,057
  • 50
  • 264
  • 435
2

You might be best using classic string concatenation techniques to achieve this. You can basically just add the result into the os.system call.

You could rewrite it to something like:

import os
import glob

for file in glob.iglob('/file/path/to/files/*.sam');
    command = "samtools view -S -b " + str(file) + " > " + str(file) + ".bam"
    os.system(command)

You could even use the format option instead:

command = "samtools view -S -b {} > {}.bam".format(file, file)

The python documentation does a good job about explaining how you can do these sorts of operations.