Skip to content

BINARY FILE OPERATIONS - Working with non-text files

Python
#!/usr/bin/env python3
"""
BINARY FILE OPERATIONS - Working with non-text files
Demonstrates reading and writing binary data
"""

import os
import tempfile

print("=" * 60)
print("BINARY FILE OPERATIONS - Non-Text Data")
print("=" * 60)

temp_dir = tempfile.gettempdir()

# Example 1: Writing binary data
print("\n1. Writing Binary Data")
print("-" * 40)
binary_file = os.path.join(temp_dir, "data.bin")

# Binary data (bytes)
data = bytes([0x48, 0x65, 0x6C, 0x6C, 0x6F])  # "Hello" in ASCII

with open(binary_file, 'wb') as f:
    f.write(data)
    print(f"Wrote {len(data)} bytes")
    print(f"Data: {data}")
    print(f"As hex: {data.hex()}")

# Example 2: Reading binary data
print("\n2. Reading Binary Data")
print("-" * 40)
with open(binary_file, 'rb') as f:
    read_data = f.read()
    print(f"Read {len(read_data)} bytes")
    print(f"Data: {read_data}")
    print(f"As string: {read_data.decode('ascii')}")

# Example 3: Writing numbers as binary
print("\n3. Writing Integer Data as Bytes")
print("-" * 40)
numbers_file = os.path.join(temp_dir, "numbers.bin")

numbers = [255, 128, 64, 32, 16, 8, 4, 2, 1]
with open(numbers_file, 'wb') as f:
    for num in numbers:
        f.write(num.to_bytes(1, byteorder='big'))
    print(f"Wrote {len(numbers)} bytes")

with open(numbers_file, 'rb') as f:
    read_bytes = f.read()
    print(f"Read bytes: {list(read_bytes)}")

# Example 4: Binary file copy
print("\n4. Copying a Binary File")
print("-" * 40)
source = os.path.join(temp_dir, "source.bin")
dest = os.path.join(temp_dir, "dest.bin")

# Create source with sample binary data
with open(source, 'wb') as f:
    f.write(b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09')

# Copy binary data
with open(source, 'rb') as src, open(dest, 'wb') as dst:
    data = src.read()
    dst.write(data)
    print(f"Copied {len(data)} bytes")

# Verify
with open(dest, 'rb') as f:
    verify_data = f.read()
    print(f"Verification: {list(verify_data)}")

# Example 5: Reading binary in chunks
print("\n5. Reading Binary File in Chunks")
print("-" * 40)
chunk_file = os.path.join(temp_dir, "large.bin")

# Create file with 20 bytes
with open(chunk_file, 'wb') as f:
    f.write(bytes(range(20)))

# Read in chunks of 5 bytes
chunk_size = 5
chunk_num = 0
with open(chunk_file, 'rb') as f:
    while True:
        chunk = f.read(chunk_size)
        if not chunk:
            break
        chunk_num += 1
        print(f"  Chunk {chunk_num}: {list(chunk)}")

# Example 6: Mixed binary operations
print("\n6. Binary File Header and Data")
print("-" * 40)
structured_file = os.path.join(temp_dir, "structured.bin")

# Write header and data
with open(structured_file, 'wb') as f:
    # Header: 4-byte magic number
    f.write(b'MYFT')
    # Version: 1 byte
    f.write(bytes([1]))
    # Data length: 2 bytes
    data_len = 10
    f.write(data_len.to_bytes(2, byteorder='big'))
    # Actual data
    f.write(bytes(range(data_len)))

# Read structured file
with open(structured_file, 'rb') as f:
    magic = f.read(4)
    version = f.read(1)[0]
    data_len = int.from_bytes(f.read(2), byteorder='big')
    data = f.read(data_len)

    print(f"  Magic: {magic.decode('ascii')}")
    print(f"  Version: {version}")
    print(f"  Data Length: {data_len}")
    print(f"  Data: {list(data)}")

# Example 7: Appending binary data
print("\n7. Appending to Binary File")
print("-" * 40)
append_file = os.path.join(temp_dir, "append.bin")

with open(append_file, 'wb') as f:
    f.write(b'\x01\x02\x03')
    print("  Initial: wrote 3 bytes")

with open(append_file, 'ab') as f:
    f.write(b'\x04\x05\x06')
    print("  Appended: 3 more bytes")

with open(append_file, 'rb') as f:
    all_data = f.read()
    print(f"  Total data: {list(all_data)}")

# Cleanup
for f in [binary_file, numbers_file, source, dest, chunk_file,
          structured_file, append_file]:
    if os.path.exists(f):
        os.remove(f)

print("\n" + "=" * 60)
print("Key Points:")
print("  - Use 'rb' mode for reading binary files")
print("  - Use 'wb' mode for writing binary files")
print("  - Use 'ab' mode for appending binary data")
print("  - Binary mode works with bytes objects")
print("  - Essential for images, videos, executables")
print("=" * 60)