
正文
Python学习笔记(三十五)—内置模块(4)struct
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
摘抄自:https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/001431955007656a66f831e208e4c189b8a9e9f3f25ba53000
Python提供了一个
struct
模块来解决
bytes
和其他二进制数据类型的转换。
struct
的
pack
函数把
任意数据类型
变成
bytes
:
>>> import struct
>>> struct.pack('>I', 10240099)
b'\x00\x9c@c'
pack
的第一个参数是处理指令,
'
>I
'
的意思是:
>
表示
字节顺序
是
big-endian
,也就是
网络序
,
I
表示
4字节无符号整数
。
后面的参数个数要和处理指令一致。
unpack
把
bytes
变成相应的数据类型
:
>>> struct.unpack('>IH', b'\xf0\xf0\xf0\xf0\x80\x80')
(4042322160, 32896)
根据
>IH
的说明,后面的
bytes
依次变为
I
:4字节无符号整数和
H
:2字节无符号整数。
所以,尽管Python不适合编写底层
操作字节流的
代码,但在对性能要求不高的地方,利用
struct
就方便多了。
struct
模块定义的数据类型可以参考Python官方文档:
https://docs.python.org/3/library/struct.html#format-characters
Windows的位图文件(.bmp)是一种非常简单的文件格式,我们来用
struct
分析一下。
首先找一个bmp文件,没有的话用“画图”画一个。
读入前30个字节来分析:
>>> s = b'\x42\x4d\x38\x8c\x0a\x00\x00\x00\x00\x00\x36\x00\x00\x00\x28\x00\x00\x00\x80\x02\x00\x00\x68\x01\x00\x00\x01\x00\x18\x00'
BMP格式采用 小端方式 存储数据,文件头的 结构按顺序 如下:
两个字节:'BM'表示Windows位图,'BA'表示OS/2位图;
一个4字节整数:表示位图大小;
一个4字节整数:保留位,始终为0;
一个4字节整数:实际图像的偏移量;
一个4字节整数:Header的字节数;
一个4字节整数:图像宽度;
一个4字节整数:图像高度;
一个2字节整数:始终为1;
一个2字节整数:颜色数。
所以,组合起来用
unpack
读取:
>>> struct.unpack('<ccIIIIIIHH', s)
(b'B', b'M', 691256, 0, 54, 40, 640, 360, 1, 24)
结果显示,
b'B'
、
b'M'
说明是Windows位图,位图大小为640x360,颜色数为24。
请编写一个
bmpinfo.py
,可以检查任意文件是否是位图文件,如果是,打印出图片大小和颜色数。
# -*- coding: utf-8 -*-
#检查任意文件是否是位图文件,如果是,打印出图片大小和颜色数 import os, struct def bmpinfo(thePath):
if os.path.isfile(thePath):
with open(thePath, 'rb') as f:
bThirty = f.read(30) # 读入前30个字节
if len(bThirty) < 30:
print('Not a bmp file!')
return
infos = struct.unpack('<ccIIIIIIHH', bThirty)
if infos[0] != b'B' or infos[1] != b'M':
print('Not a bmp file!')
return
print('The bmp file is %s * %s, and colors are %s.' % (infos[6], infos[7], infos[9]))
else:
print('File not exists!') if __name__ == '__main__':
print("Please input a bmp file's full path:")
p = input()
bmpinfo(p)








