大家好,又见面了,我是全栈君
struct是Python中的内建模块,用来在C语言中的结构体与Python中的字符串之间进行转换,数据一般来自文件或网络
1. 功能
(1) 按照指定格式将Python数据转换为字符串(该字符串为字节流)
(2) 按照指定格式将字节流转换为Python指定的数据类型
(3) 处理二进制数据,如果用struct来处理文件的话,需要用‘wb’/’rb’以二进制写,读的方式来处理文件
(4) 处理C语言中的结构体
2. struct常用方法
(1) pack(fmt, v1, v2, …) -> bytes
按照给定的格式将数据转换成字符串(字节流)
(2) pack_into(fmt, buffer, offset, v1, v2, …)
按照给定的格式将数据转换成字符串(字节流),并将字节流写入以offset开始的buffer中
(3) unpack(fmt, buffer) -> (v1, v2, …)
按照给定的格式解析字节流并返回结果
(4) unpack_from(fmt, buffer, offset=0) -> (v1, v2, …)
按照指定的格式解析以offset开始的缓冲区并返回解析结果
(5) calcsize(fmt) -> integer
计算给定的格式占多少字节的内存,注意对齐方式
3. 格式符
格式化字符串:指定数据类型、控制字节顺序、大小和对齐方式
下面2张表来自官网
Character | Byte order | Size | Alignment |
---|---|---|---|
@ | native | native | 凑够4字节 |
= | native | standard | 按原字节数 |
< | little-endian | standard | 按原字节数 |
> | big-endian | standard | 按原字节数 |
! | network (= big-endian) | standard | 按原字节数 |
Format | C Type | Python type | Standard size | Notes |
---|---|---|---|---|
x | pad byte | no value | ||
c | char | string of length 1 | 1 | |
b | signed char | integer | 1 | (3) |
B | unsigned char | integer | 1 | (3) |
? | _Bool | bool | 1 | (1) |
h | short | integer | 2 | (3) |
H | unsigned short | integer | 2 | (3) |
i | int | integer | 4 | (3) |
I | unsigned int | integer | 4 | (3) |
l | long | integer | 4 | (3) |
L | unsigned long | integer | 4 | (3) |
q | long long | integer | 8 | (2), (3) |
Q | unsigned long long | integer | 8 | (2), (3) |
f | float | float | 4 | (4) |
d | double | float | 8 | (4) |
s | char[] | string | ||
p | char[] | string | ||
P | void * | integer | (5), (3) |
4. 示例
代码语言:javascript复制#coding=utf-8
''' struct实现二进制文件的读写 '''
import sys
import struct
def writefile(path):
name = b"zhanglin"
age = 30
sex = b"female"
profession = b"IT"
try:
with open(path, "wb") as pf:
text = struct.pack(">8si6s2s", name,age,sex,profession)
pf.write(text)
print ("write file success!")
except Exception as e:
print ("write file faild!:",e)
def readfile(path):
text = None
try:
with open(path, "rb") as pf:
text = pf.read()
print ("read file success!")
print (text)
print (struct.unpack(">8si6s2s", text))
except Exception as e:
print ("read file faild!:",e)
if __name__ == "__main__":
path = sys.argv[1]
writefile(path)
readfile(path)
输出结果:
>>> D:Pystu>python struct_test.py struct_test.txt
>>> write file success!
>>> read file success!
>>> b'zhanglinx00x00x00x1efemaleIT'
>>> (b'zhanglin', 30, b'female', b'IT')
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/120204.html原文链接:https://javaforall.cn