从fi读取结构数组

2024-10-01 11:19:47 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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。在


Tags: topath数组open结构structlongfile
2条回答

唉,对于数组来说,没有类似的方法可以容纳复杂的结构。在

通常的方法是多次调用解包结构并将结果附加到列表中。在

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

如果你关心的是效率,那就知道解包结构在连续调用之间缓存解析的结构。在

我将看到mmaping文件,然后使用来自\u buffer()调用的ctypes类方法。 这将映射ctypes定义的结构数组http://docs.python.org/library/ctypes#ctypes-arrays。在

这将结构映射到mmap文件上,而不必显式地读取/转换和复制内容。在

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

这里是一个使用mmap的简单示例。(我用dddd 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)

相关问题 更多 >