title: How to split a multi-fasta file into chunks of equal sequence length AND change the headers using biopython
body: <p>First, I apologize for my pythonic ignorance. I need to break up my multi-sequence fasta file into equal sized chunks for a pipeline downstream. I haven't run across anything that does this easily or in the format I'm looking for.</p>
  
  <p>An example fasta file input:</p>
  
  <h3>original.fas</h3>
  
  >contig1
  
  <p>ACGTA</p>
  
  >contig2
  
  <p>GGGATAGTCA</p>
  
  >contig3
  
  <p>GACTACTTTT</p>
  
  <p>The above example fasta has 25bp. If I set the "chunk number" parameter to '4', then I would expect my output files to all have 7 base pairs, except for the last file which would have the remainder 4bp. It would look like this:</p>
  
  <h3>chunk1.fas</h3>
  
  >contig1:0-4
  
  <p>ACGTA</p>
  
  >contig2:0-1
  
  <p>GG</p>
  
  <h3>chunk2.fas</h3>
  
  >contig2:2-7
  
  <p>GATAGTC</p>
  
  <h3>chunk3.fas</h3>
  
  >contig2:9-9
  
  <p>A</p>
  
  >contig3:0-5
  
  <p>GACTAC</p>
  
  <h3>chunk4.fas</h3>
  
  >contig3:6-9
  
  <p>TTTT</p>
  
  <p>Notice each resulting chunk*.fas includes 7 base pairs, except for the leftover base pairs in chunk4.fas. Also, each resulting sequence header in the chunk files have changed from the original, so that they include a ":" as well as a "start" and "stop" location derived from the original sequence.</p>
  
  <p>The biopython cookbook has a pretty nice batch size iterator tool and I think my answer resides within manipulating this code, but I haven't a clue how to go about this. </p>
  
  <p>Any help is appreciated. Cheers.</p>
  
  <pre><code>
  def batch_iterator(iterator, batch_size):
      """Returns lists of length batch_size.
      This can be used on any iterator, for example to batch up
      SeqRecord objects from Bio.SeqIO.parse(...), or to batch
      Alignment objects from Bio.AlignIO.parse(...), or simply
      lines from a file handle.
      This is a generator function, and it returns lists of the
      entries from the supplied iterator.  Each list will have
      batch_size entries, although the final list may be shorter.
      """
      entry = True  # Make sure we loop once
      while entry:
          batch = []
          while len(batch) &lt; batch_size:
              try:
                  entry = next(iterator)
              except StopIteration:
                  entry = False
              if not entry:
                  # End of file
                  break
              batch.append(entry)
          if batch:
              yield batch
  
  record_iter = SeqIO.parse('aVan.fa', 'fasta')
  
  for i, batch in enumerate(batch_iterator(record_iter, 1000), start=1):
      filename = 'group_{}.fasta'.format(i)
      count = SeqIO.write(batch, filename, 'fasta')
      print('Wrote {} records to {}'.format(count, filename))
  </code></pre>