繁体   English   中英

从文件中读取结构数组

[英]Readng an array of structures from file

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

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倍的struct并将其附加到列表是一种开销。 我不想使用像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)

las,没有类似的数组可以保存复杂的结构。

通常的技术是对struct.unpack进行多次调用,并将结果附加到列表中。

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)

如果您担心效率问题,请知道struct.unpack在连续调用之间缓存已解析的结构。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM