python - 从文件中读取结构体数组

标签 python struct

我有下一个任务:我需要从文件中读取结构数组。 读取一个结构没有问题:

structFmt = "=64s 2L 3d"    # char[ 64 ] long[ 2 ] double [ 3 ]
structLen = struct.calcsize( structFmt )
f = open( "path/to/file", "rb" )
structBytes = f.read( structLen )
s = struct.unpack( structFmt, structBytes )

读取“简单”类型的数组也没有问题:

f = open( "path/to/file", "rb" )
a = array.array( 'i' )
a.fromfile( f, 1024 )

但是从文件中读取 1024 个结构 structFmt 是有问题的(当然对我来说)。 我认为,读取 1024 次结构并将其附加到列表中是一种开销。 我不想使用像 numpy 这样的外部依赖项。

最佳答案

我将查看映射文件,然后使用 ctypes 类方法 from_buffer() 调用。 这将映射 ctypes 定义的结构数组 http://docs.python.org/library/ctypes#ctypes-arrays .

这会将结构映射到 mmap 文件上,而无需显式读取/转换和复制内容。

我不知道最终结果是否合适。

只是为了好玩,这里是一个使用 mmap 的快速示例。 (我使用 dd dd if=/dev/zero of=./test.dat bs=96 count=10240

创建了一个文件
from ctypes import Structure
from ctypes import c_char, c_long, c_double
import mmap
import timeit


class StructFMT(Structure):
     _fields_ = [('ch',c_char * 64),('lo',c_long *2),('db',c_double * 3)]

d_array = StructFMT * 1024

def doit():
    f = open('test.dat','r+b')
    m = mmap.mmap(f.fileno(),0)
    data = d_array.from_buffer(m)

    for i in data:
        i.ch, i.lo[0]*10 ,i.db[2]*1.0   # just access each row and bit of the struct and do something, with the data.

    m.close()
    f.close()

if __name__ == '__main__':
    from timeit import Timer
    t = Timer("doit()", "from __main__ import doit")
    print t.timeit(number=10)

关于python - 从文件中读取结构体数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11857521/

相关文章:

python - 重叠坐标的 folium 弹出文本问题(更新 :HTML source code)

python - 在具有一行零的矩阵中,如何将矩阵的相应对角线条目替换为一?

Python,pygame鼠标位置和按下哪个按钮

python - 字典列表中是否存在 True 值?

Golang 将任何结构存储在其他结构字段中

c - C 和 .h 文件中的结构

python - 恢复 tensorflow 模型时出现NotFoundError

c++ - 为什么这个结构排序会使我的程序崩溃?

c - 结构 vector c

json - 在特定结构中解码 Json 数据