我有下一个任务:我需要从文件中读取结构数组。 读取一个结构没有问题:
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 次结构并将其附加到列表中是一种开销。
我不想使用像 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)
关于python - 从文件中读取结构体数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11857521/