我有下一个任务:我需要从文件中读取一个结构数组。 阅读一个结构没有问题:
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 )
读取“简单”类型的数组也没有问题:
^{pr2}$但从文件中读取1024个结构structFmt
有一个问题(当然对我来说)。
我认为,读取1024次struct并将其附加到一个列表是一个开销。
我不想使用外部依赖项,如numpy
。在
唉,对于数组来说,没有类似的方法可以容纳复杂的结构。在
通常的方法是多次调用解包结构并将结果附加到列表中。在
如果你关心的是效率,那就知道解包结构在连续调用之间缓存解析的结构。在
我将看到mmaping文件,然后使用来自\u buffer()调用的ctypes类方法。 这将映射ctypes定义的结构数组http://docs.python.org/library/ctypes#ctypes-arrays。在
这将结构映射到mmap文件上,而不必显式地读取/转换和复制内容。在
我不知道最终结果是否合适。在
这里是一个使用mmap的简单示例。(我用dd
dd if=/dev/zero of=./test.dat bs=96 count=10240
创建了一个文件相关问题 更多 >
编程相关推荐