Table of Contents
Use bytearray()
Function
To write a binary file in Python:
- Use the
bytearray()
function to convert the list of bytes to abytearray
type object. - Use a
with
clause withopen()
the method in write binary mode(wb
) - Use
write()
method to write thebyte_array
to the file.
1 2 3 4 5 6 7 8 9 10 11 |
byte_list = [100, 56, 35, 94] byte_array = bytearray(byte_list) try: with open("bytes_array.txt", 'wb') as f: f.write(byte_array) print(str(byte_array) + " successfully stored in a file...") except Exception as e: print(e) |
1 2 3 |
bytearray(b'd8#^') successfully stored in a file... |
We created a byte_list
using a sequence of values from 0
to 255
in binary form.
The bytearray() function is a built-in function in Python that takes an iterable to convert it into an array of bytes.It is an object constructor for a mutable array of bytes, like a list
, but unordered. From an iterable of integers, it only accepts values in the range(256)
, or the function throws a ValueError: byte must be in range(0, 256)
.
We used the bytearray()
function to convert the byte_list
to the byte_array
. To successfully write the byte_array
to the file, we used Python’s try-except control flow statement. It handles errors and exceptions without disrupting the flow of the program.
We used the with keyword to wrap the code block of writing the byte_array
to the bytes_array.txt
file. Next, we used the open() function to open a file for reading, or writing is a built-in function in Python. It took two arguments: the filename and the mode.
The mode is an optional argument. It defaults to r
(read) if it’s not specified. We specified the mode as wb
to create or truncate the existing file named bytes_array.txt
as binary. The write()
function wrote the byte_array
to the bytes_array.txt
file.
Use bytes()
Function
To write a binary file in Python:
- Use the
bytes()
function to convert the list of bytes to abytes
type object. - Use a
with
clause withopen()
the method in write binary mode(wb
) - Use
write()
method to write thebyte_array
to the file.
1 2 3 4 5 6 7 8 9 10 11 |
byte_list = [100, 56, 35, 94] byte_array = bytes(byte_list) try: with open("bytes_array.txt", 'wb') as f: f.write(byte_array) print(str(byte_array) + " successfully stored in a file...") except Exception as e: print(e) |
1 2 3 |
b'd8#^' successfully stored in a file... |
We have already discussed the creation of the byte_list
, try-except
clause, with
keyword, and open()
and write()
functions while explaining the code snippet using the bytearray()
function.
In this section, we used the bytes()
function, similar to the bytearray()
function but returned an immutable sequence of bytes
type. We used this function to convert a byte_list
to a byte_array
. Once we got the byte_array
, we used the write()
function to write the byte_array
to the bytes_array.txt
file.
Use struct.pack()
Function
To write a binary file in Python:
- Use the
struct.pack()
function to convert the list of bytes to abytes
type object. - Use a
with
clause withopen()
the method in write binary mode(wb
) - Use
write()
method to write thebyte_array
to the file.
1 2 3 4 5 6 7 8 9 10 11 |
import struct byte_list = [100, 56, 35, 94] byte_array = struct.pack('4B', *byte_list) try: with open("bytes_array.txt", 'wb') as f: f.write(byte_array) print(str(byte_array) + " successfully stored in a file...") except Exception as e: print(e) |
1 2 3 |
b'd8#^' successfully stored in a file... |
After successfully creating the byte_list
, we imported the struct
library.
Python’s struct module is a collection of functions that are used with binary data to perform operations such as packing, unpacking, and analyzing the contents of structs like C-structure formats. We imported it to process the byte_list
.
The library provides the struct.pack() function that converts regular Python data types into packed binary data. It holds two arguments, as listed below.
fmt
– specifies the format in which the objects are to be packed.vals
– contains any number of parameters needed to create the binary representation required for each element specified in thefmt
parameter.
We used the 4B
format to convert the byte_list
into packed byte_array
of the bytes
data type. We used try-except
blocks to handle the errors properly. Finally, we used the open()
and write()
functions to open the file and write the array to the byte_array.txt
file.
Further reading:
Use encode()
Function with join()
To write a binary file in Python:
- Use the
join()
function to combine list elements aschar
. - Use the
encode()
function to convert the string of bytes to abytes
type object. - Use a
with
clause withopen()
the method in write binary mode(wb
) - Use
write()
method to write thebyte_array
to the file.
1 2 3 4 5 6 7 8 9 10 |
byte_list = [100, 56, 35, 94] byte_array = ''.join(chr(byte) for byte in byte_list).encode('charmap') try: with open("bytes_array.txt", 'wb') as f: f.write(byte_array) print(str(byte_array) + " successfully stored in a file...") except Exception as e: print(e) |
1 2 3 |
b'd8#^' successfully stored in a file... |
The join() function in Python is a built-in method that combines multiple strings into one string. It takes an iterable object as an argument and returns a single string formed from the elements of the iterable object separated by a separator character(s). We used the join()
function to join the elements of byte_list
as char
.
The encode() function represents data in an alternative form. It converts information from one format to another, such as text to binary or vice versa. The purpose of encoding is to make the data more secure and easier to access and store.
We applied the encode()
function on byte_array
to convert it into a bytes
type object and then wrote the array to the file using the open()
and write()
functions wrapped under the with
statement.
Use to_bytes()
Function
To write a binary file in Python:
- Use
with
keyword with theopen()
function to open the file. - Use the
for
loop to iterate every element in the list of bytes. - Use the
to_bytes()
function on every element to convert it to a byte. - Use the
write()
function to write the byte to the file.
1 2 3 4 5 6 7 8 9 10 |
byte_list = [100, 56, 35, 94] try: with open("bytes_array.txt", 'wb') as f: for byte in byte_list: f.write(byte.to_bytes(1, byteorder='big')) print("Successfully stored in a file...") except Exception as e: print(e) |
1 2 3 |
Successfully stored in a file... |
We created the byte_list
of integers in the range(0-255)
. Then, after opening the file using the open()
function, we used the for
loop to iterate every element of byte_list
.
Python’s to_bytes() function provides a convenient way to convert various built-in data types, such as integers, into an equivalent representation in bytes of specified size. It enables the user to easily store or manipulate data represented as a sequence of bytes. The function holds arguments:
- The
length
to ensure that the result has enough bytes to represent the number without data loss. - The
byteorder
specifies an endian encoding that represents the integer.
We applied the to_bytes()
function over every element of byte_list
and wrote the returned byte
to the file.