MST

星途 面试题库

面试题:Python 二进制文件读写中的数据结构处理

假设有一个自定义的结构体数据,例如包含 `int` 类型的 ID 和 `char[10]` 类型的名称,使用 Python 如何将这样的数据以二进制形式写入文件,并在之后准确无误地读取出来?请写出完整代码,并解释在处理不同数据类型时所使用的方法及原理。
37.5万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试
import struct


class CustomStruct:
    def __init__(self, id_num, name):
        self.id = id_num
        self.name = name


def write_struct_to_file(struct_obj, file_path):
    with open(file_path, 'wb') as f:
        packed_id = struct.pack('!i', struct_obj.id)
        name_bytes = struct_obj.name.encode('utf-8')
        # 确保name为10个字节,如果不足10个字节,使用空格填充
        name_bytes = name_bytes.ljust(10, b' ')
        f.write(packed_id)
        f.write(name_bytes)


def read_struct_from_file(file_path):
    with open(file_path, 'rb') as f:
        packed_id = f.read(4)
        id_num = struct.unpack('!i', packed_id)[0]
        name_bytes = f.read(10)
        name = name_bytes.decode('utf-8').rstrip()
        return CustomStruct(id_num, name)


# 示例使用
if __name__ == "__main__":
    custom_struct = CustomStruct(123, "example")
    write_struct_to_file(custom_struct, "test.bin")
    read_struct = read_struct_from_file("test.bin")
    print(f"ID: {read_struct.id}, Name: {read_struct.name}")


代码解释

  1. 导入 struct 模块struct 模块用于处理 C 结构的二进制数据。它提供了 packunpack 函数,用于将 Python 值转换为 C 结构的二进制表示,以及将二进制数据解析为 Python 值。
  2. 定义 CustomStruct:这是自定义的结构体,包含 idint 类型)和 namechar[10] 类型在 Python 中使用长度为10的字符串模拟)。
  3. write_struct_to_file 函数
    • 以二进制写入模式打开文件。
    • 使用 struct.pack('!i', struct_obj.id)int 类型的 id 打包成网络字节序(大端序,由 ! 表示)的二进制数据。i 表示 int 类型。
    • name 编码为字节串,并使用 ljust 方法确保长度为10个字节,不足则用空格填充。
    • 依次将打包后的 id 和处理后的 name 字节串写入文件。
  4. read_struct_from_file 函数
    • 以二进制读取模式打开文件。
    • 读取4个字节(int 类型的大小)作为 packed_id,然后使用 struct.unpack('!i', packed_id) 解包为 int 类型的 id_num
    • 读取10个字节作为 name_bytes,将其解码为字符串,并使用 rstrip 方法去除可能存在的填充空格。
    • 返回一个新的 CustomStruct 对象。
  5. 示例使用:创建一个 CustomStruct 对象,将其写入文件,然后从文件中读取并打印内容,验证写入和读取的准确性。