How to open a binary file in append mode with Python?

In Python, to open a binary file in append mode, we can use the open() function with the mode set to ab. This allows us to open an existing file or create a new one if it doesn't exist.

Understanding 'ab' Mode

In the mode 'ab', the 'a' stands for append mode, which allows us to add new data to the end of the file without truncating its existing content. The 'b' stands for binary mode, used when handling files containing non-text data.

Binary files can include image files (JPEG, PNG), audio files (MP3, WAV), video files (MP4), or executable files.

Syntax

with open('filename', 'ab') as file:  
    # Write binary data to the file  
    file.write(b'binary data')

Writing Binary Data

When working with binary data, ensure your data is in bytes format using byte literals. Here's a practical example ?

# Create and append to a binary file
with open('example.bin', 'ab') as file:
    # Binary data to append
    data_to_append = b'\x48\x65\x6c\x6c\x6f'  # "Hello" in bytes
    file.write(data_to_append)
    print("Data appended successfully")
Data appended successfully

Reading Binary Data After Appending

To verify what was written, you need to open the file in binary read mode ('rb') ?

# First, write some data
with open('test.bin', 'ab') as file:
    file.write(b'\x01\x02\x03\x04')

# Then read it back
with open('test.bin', 'rb') as file:
    content = file.read()
    print(f"File content: {content}")
    print(f"Content length: {len(content)} bytes")
File content: b'\x01\x02\x03\x04'
Content length: 4 bytes

Appending to Existing Binary Files

When you append to an existing binary file, new data is added to the end ?

# Create initial file
with open('data.bin', 'wb') as file:
    file.write(b'\xFF\xFE')

# Append more data
with open('data.bin', 'ab') as file:
    file.write(b'\xFD\xFC')

# Read final content
with open('data.bin', 'rb') as file:
    final_content = file.read()
    print(f"Final content: {final_content}")
Final content: b'\xff\xfe\xfd\xfc'

Key Features of 'ab' Mode

Feature Description
File Creation Creates new file if it doesn't exist
Cursor Position Always positioned at end of file
Data Format Requires bytes object (not strings)
Existing Data Preserved - no truncation occurs

Common Use Cases

Binary append mode is useful for:

  • Adding entries to log files in binary format
  • Appending frames to video files
  • Adding records to database files
  • Extending compressed archives

Conclusion

Use 'ab' mode to append binary data to files without overwriting existing content. Always ensure your data is in bytes format and use 'rb' mode to read binary files back.

---
Updated on: 2026-03-24T17:19:11+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements