2

我需要用 Python 编写一长串整数和浮点数,就像fwrite在 C 中一样——以二进制形式。

这是为我正在使用的另一段代码创建输入文件所必需的。

做这个的最好方式是什么?

4

2 回答 2

5

您可以使用struct模块非常简单地做到这一点。

例如,要以二进制形式编写一个 32 位整数列表:

import struct

ints = [10,50,100,2500,256]
with open('output', 'w') as fh:
    data = struct.pack('i' * len(ints), *ints)
    fh.write(data)

将会写'\n\x00\x00\x002\x00\x00\x00d\x00\x00\x00\xc4\t\x00\x00\x00\x01\x00\x00'

于 2013-05-16T23:30:53.347 回答
3

看看 numpy: numpy tofile :

使用数组方法“tofile”,您可以编写二进制数据:

# define output-format
numdtype = num.dtype('2f')

# write data
myarray.tofile('filename', numdtype)

另一种方法是使用 memmaps:numpy memmaps

# create memmap                                              
data = num.memmap('filename', mode='w+', dtype=num.float, offset=myoffset, shape=(my_shape), order='C')
# put some data into in:
data[1:10] = num.random.rand(9)
# flush to disk:
data.flush()
del data
于 2013-05-16T22:30:57.883 回答