# write byte string to a binary file
s = 'Café is great\n Really?'
o = open('output.bin', 'wb')
o.write(s.encode('utf-8'))
o.close()
# read byte string from a binary file
f = open('output.bin', 'rb')
try:
b = f.read(1)
while b:
b = f.read(1)
print(b, type(b))
except Exception as e:
print(e)
f.close()
f = open('output.bin', 'rb')
f.tell() # current stream position
# seek(offset, from_where)
# front_where, 0, start of the stream, 1, current position, 2, end of the stream
f.seek(1, 0)
f.read(1) # b'a'
f.seek(0, 1)
f.read(1)
f.seek(-1, 2)
f.read(1)
f.close()
f = open('output.bin', 'rb')
#f.read(4) # read the first four bytes, b'Caf\xc3'
#f.read() # read all content, b'Caf\xc3\xa9 is great\n Really?'
f.readline() # read a line
b'Caf\xc3\xa9 is great\n'
import struct
# struct.pack(fmt, values)
# fmt, i, int, f, float, s, string, h, short, l, long
data_pack = struct.pack('iif', 6, 19, 4.73) # bytes
# unpack bytes
struct.unpack('iif', data_pack )
record = b'raymond\x32\x12\x08\x01\x08'
# 7 chars, int, int, int
struct.unpack('<7sHHb', record)
# list of int
l = list(range(10))
struct.pack('%si' % len(l), *l)
# list of float
l = [3.14, 4.21, 5.67]
struct.pack('%sf' % len(l), *l)
# write bytes into a binary file
o = open('output.bin', 'wb')
o.write(b'Hello')
o.write(struct.pack('iif', 6, 19, 4.73)) # big or little
o.write(struct.pack('%sf' % len(l), *[3.14, 4.21, 5.67]))
o.close()
# get the sizes of types
struct.calcsize('i') # 4
struct.calcsize('f') # 4
struct.calcsize('iif') # 12
# read data from a binary file
f = open('output.bin', 'rb') # read str
#struct.unpack('5s', f.read(5))[0] # b'Hello'
#struct.unpack('i', f.read(4))[0] # 6
#struct.unpack('i', f.read(4))[0] # 19
#struct.unpack('f', f.read(4))[0] # 4.73
struct.unpack('<5siif', f.read(17)) # (b'Hello', 6, 19, 4.730000019073486)
struct.unpack('3f', f.read(12)) # (3.140000104904175, 4.210000038146973, 5.670000076293945)
# str and bytes
s = 'Café is great\n Really?' # str
s_bytes = s.encode('utf-8') # bytes
s_bytes.decode('utf-8') # str
'Café is great\n Really?'
a = 123
b = 456
# write numbers into a binary file
o = open('output.bin', 'wb')
o.write(a.to_bytes(4, 'big')) # big or little
o.write(b.to_bytes(4, 'big'))
o.close()
# read numbers from a binary file
with open('output.bin', 'rb') as file:
a = int.from_bytes(file.read(4), byteorder='big')
b = int.from_bytes(file.read(4), byteorder='big')
print(a, b)
import struct
pi = 3.14
a = struct.pack("f", pi) # b'\xc3\xf5H@'
struct.unpack("f", a)[0] # 3.140000104904175
3.140000104904175
# list of int
l = [55, 33, 22]
data_pack = bytes(l) # b'7!\x16'
list(data_pack) # [55, 33, 22]
# list of float
l = [3.14, 4.12, 5.67]
data_pack = struct.pack('%sf'%len(l), *l)
struct.unpack('<3f', data_pack) # (3.140000104904175, 4.119999885559082, 5.670000076293945)
(3.140000104904175, 4.119999885559082, 5.670000076293945)
f = open('slick.bin', 'rb')
content = f.read()
struct.unpack('h', content[:2]) # 1280
struct.unpack('<5s', content[2:7])[0] # b'Slick'