I have to read and write binary data, where each element of data:
Is it possible without using any external module? If yes,
To open a file in binary format, add 'b' to the mode parameter. Hence the "rb" mode opens the file in binary format for reading, while the "wb" mode opens the file in binary format for writing.
Initialize the variables with data. If file open successfully, write the binary data using write method. Close the file for writing. Open the binary file to read.
"Binary" files are any files where the format isn't made up of readable characters. Binary files can range from image files like JPEGs or GIFs, audio files like MP3s or binary document formats like Word or PDF. In Python, files are opened in text mode by default.
I think you are best off using the array
module. It stores data in system byte order by default, but you can use array.byteswap()
to convert between byte orders, and you can use sys.byteorder
to query the system byte order. Example:
# Create an array of 16-bit signed integers
a = array.array("h", range(10))
# Write to file in big endian order
if sys.byteorder == "little":
a.byteswap()
with open("data", "wb") as f:
a.tofile(f)
# Read from file again
b = array.array("h")
with open("data", "rb") as f:
b.fromfile(f, 10)
if sys.byteorder == "little":
b.byteswap()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With