Harris
Harris

Reputation: 127

Writing to a binary file python

I want to write something to a binary file using python.

I am simply doing:

import numpy as np

f = open('binary.file','wb')
i=4
j=5.55
f.write('i'+'j') #where do i specify that i is an integer and j is a double?

g = open('binary.file','rb')
first = np.fromfile(g,dtype=np.uint32,count = 1)
second = np.fromfile(g,dtype=np.float64,count = 1)

print first, second

The output is just: [] []

I know it is very easy to do this in Matlab "fwrite(binary.file, i, 'int32');", but I want to do it in python.

Upvotes: 1

Views: 7924

Answers (2)

Artagel
Artagel

Reputation: 396

That's because you are trying to write a string(edited) into a binary file. You also don't close the file before trying to read it again.
If you want to write ints or strings to a binary file try adding the below code:

import numpy as np
import struct

f = open('binary.file','wb')
i = 4
if isinstance(i, int):
    f.write(struct.pack('i', i)) # write an int
elif isinstance(i, str):
    f.write(i) # write a string
else:
    raise TypeError('Can only write str or int')

f.close()

g = open('binary.file','rb')
first = np.fromfile(g,dtype=np.uint32,count = 1)
second = np.fromfile(g,dtype=np.float64,count = 1)

print first, second    

I'll leave it to you to figure out the floating number.

print first, second
[4] []

The more pythonic file handler way:

import numpy as np
import struct

with open ('binary.file','wb') as f:
    i = 4
    if isinstance(i, int):
        f.write(struct.pack('i', i)) # write an int
    elif isinstance(i, str):
        f.write(i) # write a string
    else:
        raise TypeError('Can only write str or int')

with open('binary.file','rb') as g:
    first = np.fromfile(g,dtype=np.uint32,count = 1)
    second = np.fromfile(g,dtype=np.float64,count = 1)

print first, second    

Upvotes: -1

Mad Physicist
Mad Physicist

Reputation: 114518

You appear to be having some confusion about types in Python.

The expression 'i' + 'j' is adding two strings together. This results in the string ij, which is most likely written to the file as two bytes.

The variable i is already an int. You can write it to a file as a 4-byte integer in a couple of different ways (which also apply to the float j):

  1. Use the struct module as detailed in how to write integer number in particular no of bytes in python ( file writing). Something like this:

    import struct
    with open('binary.file', 'wb') as f:
        f.write(struct.pack("i", i))
    

    You would use the 'd' specifier to write j.

  2. Use the numpy module to do the writing for you, which is especially convenient since you are already using it to read the file. The method ndarray.tofile is made just for this purpose:

    i = 4
    j = 5.55
    with open('binary.file', 'wb') as f:
        np.array(i, dtype=np.uint32).tofile(f)
        np.array(j, dtype=np.float64).tofile(f)
    

Note that in both cases I use open as a context manager when writing the file with a with block. This ensures that the file is closed, even if an error occurs during writing.

Upvotes: 4

Related Questions