Thursday, December 26, 2024
Google search engine
HomeLanguagesPython – Write Bytes to File

Python – Write Bytes to File

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:

  1. Open file
  2. Perform operation
  3. 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.

Write Bytes to File in Python

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. 

Python3




some_bytes = b'\xC3\xA9'
 
# Open in "wb" mode to
# write a new file, or
# "ab" mode to append
with open("my_file.txt", "wb") as binary_file:
   
    # Write bytes to file
    binary_file.write(some_bytes)


Output:

Write Bytes to File

my_file.txt

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.

Python3




some_bytes = b'\x21'
 
# Open file in binary write mode
binary_file = open("my_file.txt", "wb")
 
# Write bytes to file
binary_file.write(some_bytes)
 
# Close file
binary_file.close()


Output:

Write Bytes to File

my_file.txt

Example 3: Also, some_bytes can be in the form of bytearray which is mutable, or bytes object which is immutable as shown below.

Python3




# Create bytearray
# (sequence of values in
# the range 0-255 in binary form)
 
# ASCII for A,B,C,D
byte_arr = [65,66,67,68]
some_bytes = bytearray(byte_arr)
 
# Bytearray allows modification
# ASCII for exclamation mark
some_bytes.append(33)
 
# Bytearray can be cast to bytes
immutable_bytes = bytes(some_bytes)
 
# Write bytes to file
with open("my_file.txt", "wb") as binary_file:
    binary_file.write(immutable_bytes)


Output:

Write Bytes to File

my_file.txt

Example 4: Using the BytesIO module to write bytes to File

Python3




from io import BytesIO
 
write_byte = BytesIO(b"\xc3\x80")
 
with open("test.bin", "wb") as f:
    f.write(write_byte.getbuffer())


Output:

Write Bytes to File

test.bin

RELATED ARTICLES

Most Popular

Recent Comments