binary files

# Read the original image and write to a new file
original_file = open('image.jpg', 'rb')  # 'rb' = read binary
copy_file = open('image_copy.jpg', 'wb')  # 'wb' = write binary

# Read and write in chunks to handle large files
while True:
    chunk = original_file.read(4096)  # Read 4KB at a time
    if not chunk:
        break
    copy_file.write(chunk)

# Close the files
original_file.close()
copy_file.close()

print("Image copied successfully!")

Method 1: Using shutil (Easiest)

python

import shutil

# Copy image.jpg to image_copy.jpg
shutil.copy2('image.jpg', 'image_copy.jpg')

print("Image copied successfully!")

Method 2: Manual Copy with File Operations

python

# Read the original image and write to a new file
with open('image.jpg', 'rb') as original_file:  # 'rb' = read binary
    with open('image_copy.jpg', 'wb') as copy_file:  # 'wb' = write binary
        # Read and write in chunks to handle large files
        while True:
            chunk = original_file.read(4096)  # Read 4KB at a time
            if not chunk:
                break
            copy_file.write(chunk)

print("Image copied successfully!")

Method 3: Super Simple One-liner

python

# Read entire file and write it (good for small files)
with open('image.jpg', 'rb') as f:
    data = f.read()
with open('image_copy.jpg', 'wb') as f:
    f.write(data)

print("Image copied!")

Complete Example with Error Handling:

python

def copy_image(original_name, copy_name):
    try:
        with open(original_name, 'rb') as original:
            with open(copy_name, 'wb') as copy:
                # Copy in chunks (efficient for large files)
                while True:
                    chunk = original.read(8192)  # 8KB chunks
                    if not chunk:
                        break
                    copy.write(chunk)
        print(f"Successfully copied {original_name} to {copy_name}")
        return True
    except FileNotFoundError:
        print("Error: Original file not found!")
    except Exception as e:
        print(f"Error: {e}")
    return False

# Usage
copy_image('photo.jpg', 'photo_backup.jpg')

Key Points:

  • Use 'rb' (read binary) and 'wb' (write binary) modes
  • shutil.copy2() is the easiest method
  • Reading in chunks is better for large files
  • Binary mode preserves all the image data exactly

The copied JPG will be identical to the original!

handle binary files in Python, you open them using the 'b' mode flag in the open() function. Binary files are read and written in bytes rather than text strings. This is essential for non-textual data like images, audio files, or executable programs.

Opening and Closing Binary Files

You must specify the binary mode when opening a file. This is done by appending 'b' to the mode string (e.g., 'rb' for read-binary, 'wb' for write-binary).

Python

# Open a file in binary write mode
with open('data.bin', 'wb') as f:
    # Write bytes to the file
    f.write(b'\x48\x65\x6c\x6c\x6f')

# Open a file in binary read mode
with open('data.bin', 'rb') as f:
    # Read bytes from the file
    content = f.read()
    print(content)

The with statement is highly recommended for binary files as it ensures the file is closed automatically.


Reading and Writing

When working with binary files, the data you read or write must be in the form of bytes objects.

  • Reading: The read() method returns a bytes object. You can specify the number of bytes to read.Pythonwith open('image.jpg', 'rb') as f: data = f.read(1024) # Read 1024 bytes print(type(data))
  • Writing: The write() method accepts a bytes object. You cannot write a standard string directly to a binary file.Pythonbinary_data = b'This is binary data' with open('output.bin', 'wb') as f: f.write(binary_data) To convert a string to bytes, you can use the encode() method with a specified encoding, such as 'utf-8'.Pythontext_string = 'Hello, world!' encoded_string = text_string.encode('utf-8') with open('text_as_bytes.bin', 'wb') as f: f.write(encoded_string)

File Position

The seek() and tell() methods work with byte offsets.

  • tell(): Returns the current position of the file pointer in bytes.
  • seek(offset, from_what): Moves the file pointer to a specific position. The offset is the number of bytes to move, and from_what can be 0 (start), 1 (current position), or 2 (end).

Python

with open('data.bin', 'wb') as f:
    f.write(b'abcdefghi')

with open('data.bin', 'rb') as f:
    f.seek(3)       # Move to the 4th byte
    print(f.read(2))  # Read 2 bytes from the current position (d, e)

    print(f.tell())   # Print the current position (5)

Similar Posts

Leave a Reply

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