def read_blocks(source, count = None, blocksize = 512): '''Read and yield block-sized strings from open file object, up to a total of count bytes. ''' while count is None or count > 0: if count is not None: blocksize = min(count, blocksize) data = source.read(blocksize) if len(data) == 0: return # End of file if count is not None: count -= len(data) yield data def write_blocks(dest, blocks): '''Write a series of blocks to open file object.''' for block in blocks: dest.write(block)