Write Binary File in Python
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 a bytes type object.
- Use a with clause with open() the method in write binary mode( wb )
- Use write() method to write the byte_array to the file.
Binary Files
Binary files are computer files that contain data in a format that can be easily read and manipulated by machines. Binary files are important because they allow programmers to work with data in a way that is both efficient and secure. This article will discuss the basics of binary files in Python, how to read and write them, and some common use cases where they are most beneficial.
How to Read a Binary File
In Python, we can use the open() function to open a binary file and read the contents.
Open a binary file in a read mode
file = open("example.bin", "rb") # Read the contents of the file and store it in a variable binary_data = file.read() # Close the file file.close() # Print the contents of the file print(binary_data)
- We open the binary file example.bin using the open() function, with the mode rb (read binary).
- We read the contents of the file using the .read() method and store it in the variable binary_data .
- We close the file using the .close() method.
- We print the contents of the file using the print() function.
Open a binary file in a read mode using the with statement
with open("example.bin", "rb") as file: binary_data = file.read() # Print the contents of the file print(binary_data)
- We open the binary file example.bin using the open() function and the mode rb (read binary) using with statement.
- We read the contents of the file using the .read() method and store it in the variable binary_data .
- We print the contents of the file using the print() function.
Using the with statement to open a file ensures that the file is closed automatically after reading its contents.
How to Write a Binary File
To write a binary file, you need to use the built-in open() function with a mode parameter of wb . This will open the file in binary mode, allowing you to write binary data to it. Here are the steps to write a binary file:
- Open the file in binary mode using the open() function with a mode parameter of wb .
- Write the binary data to the file using the write() method of the file object.
- Close the file using the close() method of the file object.
Open a file in a binary mode
file = open('binaryfile.bin', 'wb') try: ##### Write binary data to file file.write(b'\x00\x01\x02\x03\x04\x05') finally: ### Close the file file.close()
In conclusion, writing binary files is a simple process that involves opening the file in binary mode and writing binary data to it using the write() method of the file object.
A List of the File Modes for Binary Files
When working with binary files, you need to open them in the correct file mode to ensure the file is being read and/or written correctly. There are six file modes for binary files:
- rb: Read mode (binary) — opens the file for reading in binary format.
- rb+: Read and write mode (binary) — opens the file for reading and writing in binary format.
- wb: Write mode (binary) — opens the file for writing in binary format. If the file already exists, it will be truncated.
- wb+: Write and read mode (binary) — opens the file for reading and writing in binary format. If the file already exists, it will be truncated.
- ab: Append mode (binary) — opens the file for writing in binary format. New data will be written at the end of the file.
- ab+: Append and read mode (binary) — opens the file for reading and writing in binary format. New data will be written at the end of the file.
with open("file.bin", "rb") as f: data = f.read() print(data)
This code opens a binary file named file.bin in read mode using the with statement. The rb mode ensures the file is read in binary format. The read() method is used to read the entire file and the content is then printed out to the console.
with open("file.bin", "wb") as f: data = b"\x48\x65\x6c\x6c\x6f" # Hello in binary f.write(data)
This code creates a binary file named file.bin in write mode using the with statement. The wb mode ensures the file is written in binary format. The b prefix before the string literal indicates that the string is in binary format. The write() method is used to write binary data to the file. This code writes the binary data for the string Hello to the file.