'Write reads in regions to file.'

def write_data_to_file(self, regions, filename):

    bamfile = pysam.AlignmentFile(self.original_dataset.file_name, mode='rb', index_filename=self.converted_dataset.file_name)
    new_bamfile = pysam.AlignmentFile(filename, template=bamfile, mode='wb')
    for region in regions:
        chrom = region.chrom
        start = region.start
        end = region.end
        try:
            data = bamfile.fetch(start=start, end=end, reference=chrom)
        except ValueError:
            chrom = _convert_between_ucsc_and_ensemble_naming(chrom)
            try:
                data = bamfile.fetch(start=start, end=end, reference=chrom)
            except ValueError:
                return None
        for (i, read) in enumerate(data):
            new_bamfile.write(read)
    new_bamfile.close()
    bamfile.close()
