简体   繁体   English

如何用Python将变量写成二进制数据?

[英]How to write variables as binary data with Python?

I need to write a long list of ints and floats with Python the same way fwrite would do in C - in a binary form. 我需要用Python编写一个很长的int和浮点列表,就像fwrite在C中做的那样 - 以二进制形式。

This is necessary to create input files for another piece of code I am working with. 这是为我正在使用的另一段代码创建输入文件所必需的。

What is the best way to do this? 做这个的最好方式是什么?

You can do this quite simply with the struct module. 您可以使用struct模块完成此操作。

For example, to write a list of 32-bit integers in binary: 例如,要以二进制形式写入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)

Will write '\\n\\x00\\x00\\x002\\x00\\x00\\x00d\\x00\\x00\\x00\\xc4\\t\\x00\\x00\\x00\\x01\\x00\\x00' 将写'\\n\\x00\\x00\\x002\\x00\\x00\\x00d\\x00\\x00\\x00\\xc4\\t\\x00\\x00\\x00\\x01\\x00\\x00'

Have a look at numpy: numpy tofile : 看看numpy: numpy tofile

With the array-method 'tofile' you can write binary-data: 使用数组方法'tofile',您可以编写二进制数据:

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

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

Another way is to use memmaps: numpy memmaps 另一种方法是使用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

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

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