Sulabh Tiwari
Sulabh Tiwari

Reputation: 307

Python equivalent of MATLABs fopen(filename,'rb',machinetype)

Python provides a way to open a binary file using,

open(filename, 'rb')

However in Matlab one can also specify machinetype as,

fopen(filename, 'rb', machinetype)

So I am looking for a way to specify Machinetype(Intel/Motorola) in python too.

Upvotes: 0

Views: 586

Answers (1)

TheBlackCat
TheBlackCat

Reputation: 10298

In Python this is handled when reading the file, not when opening the file.

Once you open a binary file, you need to read it into some data structure. Two common ways to do this are with struct.unpack and numpy.fromfile, both of which allow you set the endianness on per-item basis. struct.unpack reads a given sequence of numbers and/or characters once, while numpy.fromfile reads it over and over again and puts the result in an array.

In both cases, putting a '>' at the beginning of the type string makes it big-endian while putting '<' makes it little-endian. So for example '>d' would be read as a little-endian double in both cases.

This allows you to read files with multiple byte orders in the same file.

Upvotes: 3

Related Questions