filter secondary alignments using pysam
Quick look at your script suggests that you are comparing the XS and AS from different reads. I would recommend removing the continue from the read.has_tag('XS') continue block.

I think that if you filter out is_secondary and is_supplementary you don't need to do the XS to AS comparison assuming whatever generated for BAM did so correctly.

for read in bam.fetch()  
    if read.is_secondary=true  
        continue
    if read.has_tag('XS') &lt;- This block stores XS and then moves on to the next read
        XS = read.get_tag('XS')  
        continue 
    if read.has_tag('AS') 
        AS = read.get_tag('AS')  
    if AS &lt; XS  &lt;- This block compares the AS of the current read to the XS of the previous read that had one.
        read.write(read)  
bam.close()