40 lines
1.2 KiB
Python
40 lines
1.2 KiB
Python
|
from struct import Struct
|
|||
|
|
|||
|
def write_records(records, format, f):
|
|||
|
# 创建一个结构体
|
|||
|
record_struct = Struct(format)
|
|||
|
# 将数组元素解包后打包放入文件
|
|||
|
for r in records:
|
|||
|
f.write(record_struct.pack(*r))
|
|||
|
|
|||
|
# 简单来说,这是什么原理呢?
|
|||
|
# 就是我知道我结构体的格式是什么样的,然后我造一个相同的结构体,然后把数据按照结构大小分块读出来,然后重新解包
|
|||
|
# 本质就是结构体的pack和unpack
|
|||
|
def read_records(format, file):
|
|||
|
record_struct = Struct(format)
|
|||
|
# b''表示直到数据返回变成b''我们就收手
|
|||
|
chunks = iter(lambda: file.read(record_struct.size), b'')
|
|||
|
|
|||
|
return (record_struct.unpack(chunk) for chunk in chunks)
|
|||
|
|
|||
|
if __name__ == '__main__':
|
|||
|
records = [
|
|||
|
(1, 2.3, 4.5),
|
|||
|
(6, 7.8, 9.0),
|
|||
|
(12, 13.4, 56.7)
|
|||
|
]
|
|||
|
|
|||
|
# 首先我们造一个二进制结构数组文件
|
|||
|
# with open('6.数据编码与处理/11.data.bin', 'wb') as f:
|
|||
|
# write_records(records, '<idd', f)
|
|||
|
|
|||
|
with open('6.数据编码与处理/11.data.bin', 'rb') as f:
|
|||
|
for rec in read_records("<idd", f):
|
|||
|
print(rec)
|
|||
|
|
|||
|
# 要进一步理解Struct,我们就要学习这个包的<idd是什么东西了
|
|||
|
|
|||
|
|
|||
|
|
|||
|
|