How To Read, Write, Append Binary Files In Python

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.

  1. The open() function in Python is used to open a file and returns a file object.
  2. 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)
  3. Here is a brief explanation of each parameter.
  4. 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.
  5. 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).
  6. 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.
  7. 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).
  8. 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.
  9. 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.
  10. closefd: This parameter specifies whether to close the file descriptor after the file object is closed. The default value is True.
  11. opener: This parameter specifies a custom opener function to be used to open the file. The default value is None.
  12. 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.

  1. To read a binary file using Python, follow these steps.
  2. Use the open() function with the ‘rb‘ mode to open the binary file and return a file object, ‘rb‘ means read binary.
  3. Read the contents of the file using the read() method of the file object.
  4. Close the file object using the close() method.
  5. 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'
  6. 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 the read() method and store it in the file_content variable. Finally, we print the contents of the file.
  7. Because the example file does not exist, then it will throw out the FileNotFoundError error.
  8. If the file exist, then it will read out the file content and print the content on the console.
  9. 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.

  1. To write to a binary file using Python, follow these steps.
  2. Use the open() function with the ‘wb‘ mode to open the binary file, ‘wb‘ means write binary.
  3. Write the contents to the file using the write() method of the file object.
  4. Close the file object using the close() method.
  5. 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
  6. 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.
  7. Then it will write the binary data in to the file.
  8. 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.

  1. To append binary data to a file in Python, we can use the ‘ab‘ mode while opening the file.
  2. Here are the steps to append binary data to a file in Python.
  3. Use the open() function with the ‘ab‘ mode to open the file in binary append mode.
  4. Write the binary data to the file using the write() method of the file object.
  5. Close the file object using the close() method.
  6. 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

  1. What Is Exclusive Creation In Python.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.