pythonsamtools

iterate through files in python script and execute bash command


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!


Solution

  • 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.