Readng an array of structures from file

倖福魔咒の 提交于 2019-12-24 04:47:07

问题


I have the next task: I need to read an array of structures from file. There is no problem to read one structure:

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 )

Also there is no problem to read an array of "simple" types:

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

But there is a problem (for me, of course) to read 1024 structures structFmt from file. I think, that it is an overhead to read 1024 times struct and append it to a list. I do not want to use external dependencies like numpy.


回答1:


I would look at mmaping the file and then using ctypes class method from_buffer() call. This will map the ctypes defined array of structs http://docs.python.org/library/ctypes#ctypes-arrays.

This maps the structs over the mmap file without having to explicitly read/convert and copy things.

I don't know if the end result will be appropriate though.

Just for fun here is a quick example using mmap. (I created a file using 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)



回答2:


Alas, there is no analog for array that holds complex structs.

The usual technique is to make many calls to struct.unpack and append the results to a list.

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)

If you're concerned about being efficient, know that struct.unpack caches the parsed structure between successive calls.



来源:https://stackoverflow.com/questions/11857521/readng-an-array-of-structures-from-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!