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

  • String Validation Methods

    Complete List of Python String Validation Methods Python provides several built-in string methods to check if a string meets certain criteria. These methods return True or False and are useful for input validation, data cleaning, and text processing. 1. Case Checking Methods Method Description Example isupper() Checks if all characters are uppercase “HELLO”.isupper() → True islower() Checks if all…

  • group() and groups()

    Python re group() and groups() Methods Explained The group() and groups() methods are used with match objects to extract captured groups from regex patterns. They work on the result of re.search(), re.match(), or re.finditer(). group() Method groups() Method Example 1: Basic Group Extraction python import retext = “John Doe, age 30, email: john.doe@email.com”# Pattern with multiple capture groupspattern = r'(\w+)\s+(\w+),\s+age\s+(\d+),\s+email:\s+([\w.]+@[\w.]+)’///The Pattern: r'(\w+)\s+(\w+),\s+age\s+(\d+),\s+email:\s+([\w.]+@[\w.]+)’Breakdown by Capture…

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

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

  • Python Input Function: A Beginner’s Guide with Examples

    The input() function in Python is used to take user input from the keyboard. It allows your program to interact with the user by prompting them to enter data, which can then be used in your code. By default, the input() function returns the user’s input as a string. Syntax of input() python Copy input(prompt) Key Points About input() Basic Examples of input() Example…

  • Indexing and Slicing in Python Lists Read

    Indexing and Slicing in Python Lists Read Indexing and slicing are fundamental operations to access and extract elements from a list in Python. 1. Indexing (Accessing Single Elements) Example 1: Basic Indexing python fruits = [“apple”, “banana”, “cherry”, “date”, “fig”] # Positive indexing print(fruits[0]) # “apple” (1st element) print(fruits[2]) # “cherry” (3rd element) # Negative indexing print(fruits[-1]) # “fig”…

Leave a Reply

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