9.14. 二进制文件的读写

python没有二进制类型,可以用string(字符串)类型来存储二进制类型数据

python处理二进制数据时可以使用python的struct模块。

struct模块中最重要的三个函数是pack(), unpack(), calcsize():

pack(fmt, v1, v2, ...)     # 按照给定的格式(fmt),返回一个包装后的字符串。

unpack(fmt, string)       # 按照给定的格式(fmt)解析字节流string,返回一个解析出来的tuple。

calcsize(fmt)               # 计算给定的格式(fmt)占用多少字节的内存

①.数据转换成字节串

import struct

a = 20
bytes = struct.pack("i", a)  # 将a变为字符串
print(bytes)

a = "hello"
b = "world!"
c = 2
d = 45.123

bytes = struct.pack("5s6sif", a.encode("utf-8"), b.encode("utf-8"), c, d)
print(bytes)

输出结果

b'\x14\x00\x00\x00'
b'helloworld!\x00\x02\x00\x00\x00\xf4}4B'

写入二进制文件到文本中

bytes = struct.pack("5s6sif", a.encode("utf-8"), b.encode("utf-8"), c, d)

binfile = open("hellobin.txt", "wb")
binfile.write(bytes)
binfile.close()
>>> a = struct.pack('!ihb',1,2,3)
>>> a
b'\x00\x00\x00\x01\x00\x02\x03'
>>> b = struct.unpack('!ihb',a)
>>> b