2

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.

This is necessary to create input files for another piece of code I am working with.

What is the best way to do this?

1
  • 14
    Use the struct module. Commented May 16, 2013 at 22:17

2 Answers 2

5

You can do this quite simply with the struct module.

For example, to write a list of 32-bit integers in binary:

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'

Sign up to request clarification or add additional context in comments.

Comments

3

Have a look at numpy: numpy tofile:

With the array-method 'tofile' you can write binary-data:

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

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

Another way is to use 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

2 Comments

This is a simple and effective solution. Thank you very much!
You don't need dtype as the argument to 'tofile'. Actually the file is incorrect if I do so

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.