0

While using the pysam module I am trying to redirect stdout to a file as follows:

bam=sys.argv[1]
samfile = pysam.AlignmentFile(bam, "rb")
for alignment in samfile:
    reverse=isReverse(alignment.flag)
    if (reverse):
        outfile = pysam.AlignmentFile("-", "w", template=samfile)
        with open('reverse.sam', 'w') as f:
            with (f):
                for s in samfile:
                    print('HEY')
                    outfile.write(s)

While the "print('HEY')" is written to reverse.sam the "outfile.write(s)" is not. What should I do so that it is?
Thanks Mark

baron
  • 1

2 Answers2

0

Shouldn't it rather be

for alignment in samfile.fetch() 

? What does

type (alignment)

yield? And what is your intention with the extra

with (f) 

context? :) From what you posted, already the outer context does not make sense.

Michael P
  • 328
  • 3
  • 8
0

Here you go.

bam_file = sys.argv[1]  # or '-' (if reading from stdin) or 'path/to/your/input.bam'
sam_file = 'path/to/your/output.sam'  # or '-' (if writing to stdout) or 'path/to/your/output.bam' (for bam file)

infile = pysam.AlignmentFile(bam_file, "rb")
outfile = pysam.AlignmentFile(sam_file, "w", template=infile)  # or "wb" if writing to bam file

i = 0

for alignment in infile:
    if alignment.is_reverse:
        outfile.write(alignment)
        i += 1

outfile.close()
infile.close()
print("Wrote {} alignments.".format(i))
obk
  • 488
  • 5
  • 12