#!/usr/bin/python
# -*- coding: utf-8 -*-

'''
5.9    将二进制数据读取到可变缓冲区中
Created on 2016年9月11日
@author: wang
'''

import os.path
def read_into_buffer(filename):
    buf = bytearray(os.path.getsize(filename))
    with open(filename, 'rb') as f:
        f.readinto(buf)
    return buf

with open('sample.bin', 'wb') as f:
    f.write(b'Hello world')
buf = read_into_buffer('sample.bin')
print(buf)
buf[0:5] = b'Hallo'
print(buf)

with open('newsample.bin', 'wb') as f :
    f.write(buf)
    
record_size = 32
buf = bytearray(record_size)
with open('somefile', 'rb') as f:
    while True:
        n = f.readinto(buf)
        if n < record_size:
            break
        print(n)
