class BitFile(file):

    def __init__(self, filename, mode):
        super(BitFile, self).__init__(filename, mode)
self.bitCount = 0
self.byte = 0

def write(self, bit):
    self.bitCount += 1
self.byte = self.byte * 2 + bit
if self.bitCount % 8 == 0:
    super(BitFile, self).write(chr(self.byte))
self.byte = 0

def close(self):
    if self.bitCount % 8 != 0:
        super(BitFile, self).write(chr(self.byte))
super(BitFile, self).close()
with BitFile('bitfile.bin', 'w') as bf:
    bf.write(1)
bf.write(1)
bf.write(1)
bf.write(0)
bf.write(0)
bf.write(0)
bf.write(0)
bf.write(0)
bf.write(1)
writing 'bits' to c++ file streams