You can do this with a combination of Biopython for writing the Fasta files and pysam for reading the BAM files:
from Bio import SeqIO, Seq, SeqRecord
out_file = "%s.fa" % os.path.splitext(in_file)
with open(out_file, "w") as out_handle:
# Write records from the BAM file one at a time to the output file.
# Works lazily as BAM sequences are read so will handle large files.
SeqIO.write(bam_to_rec(in_file), out_handle, "fasta")
"""Generator to convert BAM files into Biopython SeqRecords.
bam_file = pysam.Samfile(in_file, "rb")
for read in bam_file:
seq = Seq.Seq(read.seq)
seq = seq.reverse_complement()
rec = SeqRecord.SeqRecord(seq, read.qname, "", "")
if __name__ == "__main__":