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

  • Polymorphism

    Polymorphism is a core concept in OOP that means “many forms” 🐍. In Python, it allows objects of different classes to be treated as objects of a common superclass. This means you can use a single function or method to work with different data types, as long as they implement a specific action. 🌀 Polymorphism…

  • Indexing and Slicing for Writing (Modifying) Lists in Python

    Indexing and Slicing for Writing (Modifying) Lists in Python Indexing and slicing aren’t just for reading lists – they’re powerful tools for modifying lists as well. Let’s explore how to use them to change list contents with detailed examples. 1. Modifying Single Elements (Indexing for Writing) You can directly assign new values to specific indices. Example 1:…

  • 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…

  • Inheritance in OOP Python: Rectangle & Cuboid Example

    Rectangle Inheritance in OOP Python: Rectangle & Cuboid Example Inheritance in object-oriented programming (OOP) allows a new class (the child class) to inherit properties and methods from an existing class (the parent class). This is a powerful concept for code reusability ♻️ and establishing a logical “is-a” relationship between classes. For instance, a Cuboid is…

  •  index(), count(), reverse(), sort()

    Python List Methods: index(), count(), reverse(), sort() Let’s explore these essential list methods with multiple examples for each. 1. index() Method Returns the index of the first occurrence of a value. Examples: python # Example 1: Basic usage fruits = [‘apple’, ‘banana’, ‘cherry’, ‘banana’] print(fruits.index(‘banana’)) # Output: 1 # Example 2: With start parameter print(fruits.index(‘banana’, 2)) # Output: 3 (starts searching…

Leave a Reply

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