Python二进制文件读写

1、二进制文件读取

data_path = "data.bin"

with open(data_path, "rb") as fr:
    # 读取一个字节
    a_raw = fr.read(1)
    
    # int8小端模式解析(大小端模式根据写入时的模式设定)
    a = int.from_bytes(a_raw, "little")

    # 读取多个字节
    b_raw = fr.read(4)
    
    # int32小端模式解析(大小端模式根据写入时的模式设定)
    b = int.from_bytes(b_raw, "little")

2、二进制文件写入

out_path = "data.bin"

with open(out_path, "wb") as fw:
    # int8类型变量,变量值小于2^8
    a = 10

    # int8小端模式字节流转换,长度为1个字节
    a_raw = int.to_bytes(x, 1, "little")

    fw.write(a_raw)
    
    # int32类型变量,变量值小于2^32
    b = 10000

    # int32小端模式字节流转换,长度为4个字节
    b_raw = int.to_bytes(b, 4, "little")

    fw.write(b_raw)

你可能感兴趣的:(python,python,开发语言)