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

  • Tuples

    In Python, a tuple is an ordered, immutable (unchangeable) collection of elements. Tuples are similar to lists, but unlike lists, they cannot be modified after creation (no adding, removing, or changing elements). Key Features of Tuples: Syntax: Tuples are defined using parentheses () (or without any brackets in some cases). python my_tuple = (1, 2, 3, “hello”) or (without…

  • Anchors (Position Matchers)

    Anchors (Position Matchers) in Python Regular Expressions – Detailed Explanation Basic Anchors 1. ^ – Start of String/Line Anchor Description: Matches the start of a string, or start of any line when re.MULTILINE flag is used Example 1: Match at start of string python import re text = “Python is great\nPython is powerful” result = re.findall(r’^Python’, text) print(result) #…

  • Formatting Date and Time in Python

    Formatting Date and Time in Python Python provides powerful formatting options for dates and times using the strftime() method and parsing using strptime() method. 1. Basic Formatting with strftime() Date Formatting python from datetime import date, datetime # Current date today = date.today() print(“Date Formatting Examples:”) print(f”Default: {today}”) print(f”YYYY-MM-DD: {today.strftime(‘%Y-%m-%d’)}”) print(f”MM/DD/YYYY: {today.strftime(‘%m/%d/%Y’)}”) print(f”DD-MM-YYYY: {today.strftime(‘%d-%m-%Y’)}”) print(f”Full month: {today.strftime(‘%B %d, %Y’)}”) print(f”Abbr…

  • Data hiding

    Data hiding in Python OOP is the concept of restricting access to the internal data of an object from outside the class. 🔐 It’s a way to prevent direct modification of data and protect the object’s integrity. This is typically achieved by using a naming convention that makes attributes “private” or “protected.” 🔒 How Data…

  • Escape Sequences in Python

    Escape Sequences in Python Escape sequences are special character combinations that represent other characters or actions in strings. Here’s a complete list of Python escape sequences with two examples for each: 1. \\ – Backslash python print(“This is a backslash: \\”) # Output: This is a backslash: \ print(“Path: C:\\Users\\Name”) # Output: Path: C:\Users\Name 2. \’ – Single quote…

Leave a Reply

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