Readng An Array Of Structures From File
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 ] st
Solution 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)
Solution 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.
Post a Comment for "Readng An Array Of Structures From File"