krpytix
krpytix

Reputation: 33

Python, How to write a 2-d array to a binary File with precision (uint8, uint16)?

I'm hoping someone can explain to me how to write a binary output to a text file.

I know that in matlab, it is pretty simple, as it has the 'fwrite' function which has the following format: fwrite(fileID,A,precision)

However, I'm not sure how to translate this to python. I currently have the data stored in a 2-D numpy array and would like to write it to the file in the same way that matlab does.

I have attempted it with the following:

#let Y be the numpy matrix
with open (filepath,'wb') as FileToWrite:
    np.array(Y.shape).tofile(FileToWrite)
    Y.T.tofile(FileToWrite)

however, this didn't lead to the desired result. The file size is way to large and the data is incorrectly formatted. Ideally i should be able to specificy the data format to be uint8 or uint16 as well.

Any help would be massively appreciated.

Upvotes: 0

Views: 1155

Answers (2)

krpytix
krpytix

Reputation: 33

So, I figured it. The solution is as follows.

# let Y be the numpy matrix
with open(filepath, 'wb') as FileToWrite:
    np.asarray(Y, dtype=np.uint8).tofile(FileToWrite)

Upvotes: 2

lvand
lvand

Reputation: 375

Im not too sure how interested you are in this, but you should be able to condense the code by using a context manager for opening the file directly and writing the array to the file without needing the extra variable.

np.asarray(Y, dtype=np.uint8).tofile(filepath)

Upvotes: 0

Related Questions