Writing bytes to a file in Python
In this tutorial, we will look at how to write bytes to a binary file in Python.
Binary files contain strings of type bytes. When we read a binary file, an object of type bytes is returned. In Python, bytes are represented by hexadecimal numbers. They are prefixed with b
the character, indicating that they are bytes.
Writing bytes to a file in Python
To write bytes to a file, we will first open()
create a file object using the file_write_mode function and provide the path to the file. The file should be wb
opened in mode, which specifies the write mode for binary files. The following code shows how we write bytes to a file.
data = b"\xC3\xA9"
with open("test.bin", "wb") as f:
f.write(data)
We can also use append mode when we need to add more data to the end of an existing file - a
for example
data = b"\xC3\xA9"
with open("test.bin", "ab") as f:
f.write(data)
To write bytes at a specific location, we can use seek()
the function, specifying the position of the file pointer to read and write data. For example:
data = b"\xC3\xA9"
with open("test.bin", "wb") as f:
f.seek(2)
f.write(data)
Writing byte arrays to files in Python
We can bytearray()
create a byte array using the bytearray function. It returns a mutable bytearray bytearray
object. We can also convert it to bytes to make it immutable. In the following example, we write a byte array to a file.
arr = bytearray([1, 2, 5])
b_arr = bytes(arr)
with open("test.bin", "wb") as f:
f.write(b_arr)
Writes BytesIO
an object to a binary file
io
The module allows us to extend input and output functions and classes related to file handling. It is used to store bytes and data in chunks in a memory buffer and allows us to handle Unicode data. Here we use the method BytesIO
of the class getbuffer()
to get a read-write view of the object. See the code below.
from io import BytesIO
bytesio_o = BytesIO(b"\xC3\xA9")
with open("test.bin", "wb") as f:
f.write(bytesio_o.getbuffer())
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
Read the first line of a file in Python
Publish Date:2025/05/05 Views:192 Category:Python
-
In Python, we have built-in functions to handle different file operations. A text file contains a sequence of strings where each line \n is terminated by a newline character. In this tutorial, we will learn how to read the first line of a t
Python get file name without extension from path
Publish Date:2025/05/05 Views:81 Category:Python
-
This tutorial will demonstrate various ways to get the file name without extension from a file path in Python. Suppose our goal is to get the file name from a list of file paths that are in the form of strings, such as from the path Desktop
Calculate the time difference between two time strings in Python
Publish Date:2025/05/05 Views:182 Category:Python
-
Sometimes we have to deal with date and time related problems in programming. In Python, date and time are not data types themselves. Despite this, Python provides a large number of functions and libraries to help deal with such problems. O
Optional parameters in Python
Publish Date:2025/05/05 Views:151 Category:Python
-
In Python, there is something called default arguments. It is also called optional parameters or optional arguments in python. Parameters refer to the inputs of a function. Functions with multiple optional parameters in Python Whenever you
Writing floating point numbers to a file in Python
Publish Date:2025/05/05 Views:91 Category:Python
-
Python makes writing data to a file a seamless task. The data is written to the file in the form of strings. In this article, you will learn how to write float values to a file in Python. Writing floating point numbers to a file in Py
How to read specific lines from a file in Python
Publish Date:2025/05/05 Views:181 Category:Python
-
A common way to read files in Python is to read the file completely and then process specific lines. Reading files in Python is fast, for example, it takes about 0.67 seconds to write a 100MiB file. However, if the file size exceeds 100MB,
Calculating the arithmetic mean in Python
Publish Date:2025/05/05 Views:190 Category:Python
-
The term arithmetic mean is the average of the numbers. The mathematical formula to determine the arithmetic mean is to divide the sum of the numbers by the count. It is determined in Python in the following way. Use mathematical formulas.
Cosine Similarity in Python
Publish Date:2025/05/05 Views:81 Category:Python
-
Cosine similarity measures the similarity between two lists of vectors by calculating the cosine angle between them. If you consider the cosine function, it has a value of 1 at 0 degrees and -1 at 180 degrees. This means that for two overla
Exponential and Logarithmic Curve Fitting in Python
Publish Date:2025/05/05 Views:79 Category:Python
-
Curve fitting is a very effective tool that is widely used in analysis. Curve fitting method studies the relationship between independent variables (also called predictor variables) and dependent variable (called response variable). This me