code: def tofile(self, f):
          
          # If the bitstring is file based then we don't want to read it all
          # in to memory.
          chunksize = 1024 * 1024 # 1 MB chunks
          if not self._offset:
              a = 0
              bytelen = self._datastore.bytelength
              p = self._datastore.getbyteslice(a, min(a + chunksize, bytelen - 1))
              while len(p) == chunksize:
                  f.write(p)
                  a += chunksize
                  p = self._datastore.getbyteslice(a, min(a + chunksize, bytelen - 1))
              f.write(p)
              # Now the final byte, ensuring that unused bits at end are set to 0.
              bits_in_final_byte = self.len % 8
              if not bits_in_final_byte:
                  bits_in_final_byte = 8
              f.write(self[-bits_in_final_byte:].tobytes())
          else:
              # Really quite inefficient...
              a = 0
              b = a + chunksize * 8
              while b <= self.len:
                  f.write(self._slice(a, b)._getbytes())
                  a += chunksize * 8
                  b += chunksize * 8
              if a != self.len:
                  f.write(self._slice(a, self.len).tobytes())
docs: Write the bitstring to a file object, padding with zero bits if needed.
  
          Up to seven zero bits will be added at the end to byte align.