In Python, we can read and write binary files using the built-in open()
function with the 'rb'
and 'wb'
modes respectively. In this article, I will tell you what is the python open() function definition and syntax, how to use it to read, write, and append binary files step by step with examples.
1. Python open() Function Definition.
- The open() function in Python is used to open a file and returns a file object.
- The syntax of the open() function is as follows:
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
- Here is a brief explanation of each parameter.
- file: This parameter specifies the name of the file you want to open. It can be a string that contains the path of the file or a file-like object.
- mode: This parameter specifies the mode in which you want to open the file. The default value is ‘r‘ (read mode). Other possible values are ‘w‘ (write mode), ‘a‘ (append mode), ‘x‘ (exclusive creation mode), ‘b‘ (binary mode), and ‘t‘ (text mode, the default mode).
- buffering: This parameter specifies the buffering policy to be used. The default value is -1, which means that the buffering policy is determined by the file system.
- encoding: This parameter specifies the encoding to be used when reading or writing the file. The default value is None, which means that no encoding is used (binary mode).
- errors: This parameter specifies the error handling policy to be used if the encoding parameter is specified. The default value is None, which means that the error handling policy is determined by the codec.
- newline: This parameter specifies the character used to represent the end of a line. The default value is None, which means that the default platform-specific newline character is used.
- closefd: This parameter specifies whether to close the file descriptor after the file object is closed. The default value is True.
- opener: This parameter specifies a custom opener function to be used to open the file. The default value is None.
- Note: The mode and buffering parameters are mutually exclusive. You cannot specify both at the same time.
2. How To Read Binary File In Python.
- To read a binary file using Python, follow these steps.
- Use the open() function with the ‘rb‘ mode to open the binary file and return a file object, ‘rb‘ means read binary.
- Read the contents of the file using the read() method of the file object.
- Close the file object using the close() method.
- Here is an example of reading a binary file in Python.
>>> with open('binary_file.bin', 'rb') as file: ... file_content = file.read() ... print(file_content) ... Traceback (most recent call last): File "<stdin>", line 1, in <module> FileNotFoundError: [Errno 2] No such file or directory: 'binary_file.bin'
- In this example, we use a
with
statement to open the binary file'binary_file.bin'
in read binary mode ('rb'
). Then we read the contents of the file using theread()
method and store it in thefile_content
variable. Finally, we print the contents of the file. - Because the example file does not exist, then it will throw out the FileNotFoundError error.
- If the file exist, then it will read out the file content and print the content on the console.
- Please note, the content is read out as binary data, then if the file content is text content, it will read out a binary string like below.
>>> with open('/Users/songzhao/Desktop/jquery-alert.html', 'rb') as file: ... file_content = file.read() ... print(file_content) ... b'<!DOCTYPE html> \n\n<html lang="en">\n\n... </body> </html>'
3. How To Write Binary File In Python.
- To write to a binary file using Python, follow these steps.
- Use the open() function with the ‘wb‘ mode to open the binary file, ‘wb‘ means write binary.
- Write the contents to the file using the write() method of the file object.
- Close the file object using the close() method.
- Here is an example of writing to a binary file in Python.
>>> with open('binary_file.bin', 'wb') as file: ... file.write(b'This is binary data.') ... 20
- The above example source code will open a file in ‘wb‘ mode, if the file does not exist, then it will create a new one.
- Then it will write the binary data in to the file.
- If you use the write binary mode, it will overwrite the data in the file if the file exist.
4. How To Append Binary File In Python.
- To append binary data to a file in Python, we can use the ‘ab‘ mode while opening the file.
- Here are the steps to append binary data to a file in Python.
- Use the open() function with the ‘ab‘ mode to open the file in binary append mode.
- Write the binary data to the file using the write() method of the file object.
- Close the file object using the close() method.
- Here is an example of appending binary data to a file in Python:
# read out binary text from the binary file. >>> with open('/Users/songzhao/Desktop/binary_file.bin', 'rb') as file: ... file_content = file.read() ... print(file_content) ... b'This is binary data.' >>> # append new binary text to the file. >>> with open('/Users/songzhao/Desktop/binary_file.bin', 'ab') as file: ... file.write(b'This is appended binary data.') ... 29 # read out the newly added binary text in the file. >>> with open('/Users/songzhao/Desktop/binary_file.bin', 'rb') as file: ... file_content = file.read() ... print(file_content) ... b'This is binary data.This is appended binary data.' >>>
References