Python - Write Bytes to File
Last Updated :
17 May, 2025
Files are used in order to store data permanently. File handling is performing various operations (read, write, delete, update, etc.) on these files. In Python, file handling process takes place in the following steps:
- Open file
- Perform operation
- Close file
There are four basic modes in which a file can be opened― read, write, append, and exclusive creations. In addition, Python allows you to specify two modes in which a file can be handled― binary and text. Binary mode is used for handling all kinds of non-text data like image files and executable files.
Examples
Example 1: Open a file in binary write mode and then specify the contents to write in the form of bytes. Next, use the write function to write the byte contents to a binary file.
Python
some_bytes = b'\xC3\xA9'
with open("my_file.txt", "wb") as binary_file:
binary_file.write(some_bytes)
Output:
my_file.txtExplanation: This code writes a byte sequence (some_bytes) to a file in binary mode. It opens my_file.txt in wb mode, and writes the bytes (b'\xC3\xA9') to it, representing the Unicode character é. The with statement ensures the file is properly closed after writing.
Example 2: This method requires you to perform error handling yourself, that is, ensure that the file is always closed, even if there is an error during writing. So, using the "with" statement is better in this regard as it will automatically close the file when the block ends.
Python
some_bytes = b'\x21'
binary_file = open("my_file.txt", "wb")
binary_file.write(some_bytes)
binary_file.close()
Output:
my_file.txtExplanation: This code writes a byte sequence (some_bytes) to a file in binary mode. It opens my_file.txt in wb mode, writes the byte (b'\x21', representing the exclamation mark !), and then explicitly closes the file using binary_file.close().
Example 3: Also, some_bytes can be in the form of bytearray which is mutable, or bytes object which is immutable as shown below.
Python
byte_arr = [65,66,67,68]
some_bytes = bytearray(byte_arr)
some_bytes.append(33)
immutable_bytes = bytes(some_bytes)
with open("my_file.txt", "wb") as binary_file:
binary_file.write(immutable_bytes)
Output:
my_file.txtExplanation: This code creates a byte array from a list of integers, appends a byte (33 representing !), and converts it to an immutable bytes object before writing it to a file. The file my_file.txt is opened in binary write mode (wb), and the bytes object is written to it. The with statement ensures the file is closed properly after writing.
Example 4: Using the BytesIO module to write bytes to File
Python
from io import BytesIO
write_byte = BytesIO(b"\xc3\x80")
with open("test.bin", "wb") as f:
f.write(write_byte.getbuffer())
Output:
test.binExplanation: This code uses BytesIO to create an in-memory binary stream (write_byte) containing the bytes (b"\xc3\x80"). It then writes the content of the in-memory stream to a file (test.bin) in binary write mode (wb). The getbuffer() method retrieves the binary data from the BytesIO object for writing. The with statement ensures the file is properly closed after the operation.
Similar Reads
Writing to file in Python
Writing to a file in Python means saving data generated by your program into a file on your system. This article will cover the how to write to files in Python in detail.Creating a FileCreating a file is the first step before writing data to it. In Python, we can create a file using the following th
4 min read
Write a dictionary to a file in Python
A dictionary store data using key-value pairs. Our task is that we need to save a dictionary to a file so that we can use it later, even after the program is closed. However, a dictionary cannot be directly written to a file. It must first be changed into a format that a file can store and read late
3 min read
Writing CSV files in Python
CSV (Comma Separated Values) is a simple file format used to store tabular data, such as spreadsheets or databases. Each line of the file represents a data record, with fields separated by commas. This format is popular due to its simplicity and wide support.Ways to Write CSV Files in PythonBelow ar
11 min read
Convert Unicode to Bytes in Python
Unicode, often known as the Universal Character Set, is a standard for text encoding. The primary objective of Unicode is to create a universal character set that can represent text in any language or writing system. Text characters from various writing systems are given distinctive representations
2 min read
How to write to an HTML file in Python ?
Python language has great uses today in almost every field, it can be used along with other technologies to make our lives easier. One such use of python is getting the data output in an HTML file. We can save any amount of our input data into an HTML file in python using the following examples in t
2 min read
Python append to a file
While reading or writing to a file, access mode governs the type of operations possible in the opened file. It refers to how the file will be used once it's opened. These modes also define the location of the File Handle in the file. The definition of these access modes is as follows: Append Only (â
4 min read
sys.stdout.write in Python
sys.stdout.write() is a built-in Python method that writes output directly to the console without automatically adding a newline (\n). It is part of the sys module and requires import sys before use. Unlike print(), it does not insert spaces between multiple arguments, allowing precise control over
3 min read
Python | Write multiple files data to master file
Given a number of input files in a source directory, write a Python program to read data from all the files and write it to a single master file. Source directory contains n number of files, and structure is same for all files. The objective of this code is to read all the files one by one and then
2 min read
Python PIL | tobytes() Method
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The Image module provides a class with the same name which is used to represent a PIL image. The module also provides a number of factory functions, including functions to load images from files,
1 min read
Python | os.write() method
OS module in Python provides functions for interacting with the operating system. OS comes under Pythonâs standard utility modules. This module provides a portable way of using operating system dependent functionality. os.write() method in Python is used to write a bytestring to the given file descr
2 min read