Ojasa Mirai

Ojasa Mirai

Python

Loading...

Learning Level

🟢 Beginner🔵 Advanced
📖 File Fundamentals📖 Reading Files Effectively✍️ Writing Files Correctly🗂️ Working with File Paths🤝 Context Managers & Safety📊 CSV Data Processing🔄 JSON Parsing & Serialization🔐 Binary Files & Encoding⚙️ Performance & Best Practices
Python/File Io/Binary Files

🔐 Binary Files & Encoding — Non-Text Data

Learn to handle binary files like images, and understand text encoding.


🎯 Reading Binary Files

Use `"rb"` mode for binary reading.

# Read binary file (like an image)
with open("photo.jpg", "rb") as file:
    data = file.read()  # Returns bytes object

print(type(data))  # <class 'bytes'>
print(len(data))   # Size in bytes

💡 Writing Binary Files

Use `"wb"` mode for binary writing.

# Copy image file (preserves binary data perfectly)
with open("original.jpg", "rb") as source:
    image_data = source.read()

with open("copy.jpg", "wb") as dest:
    dest.write(image_data)

# File copied exactly, no corruption

🎨 Real-World Example: Copying Files

# Copy any file (text, image, zip, etc.)
def copy_file(source_path, dest_path):
    """Copy file while preserving all data"""
    with open(source_path, "rb") as source:
        data = source.read()

    with open(dest_path, "wb") as dest:
        dest.write(data)

# Works for any file type
copy_file("document.pdf", "document_copy.pdf")
copy_file("image.png", "image_copy.png")

📊 Text Encoding

Text files have encoding (usually UTF-8).

# Default encoding (usually UTF-8 on modern systems)
with open("text.txt", "r") as file:
    content = file.read()

# Explicit encoding
with open("text.txt", "r", encoding="utf-8") as file:
    content = file.read()

# Different encoding if needed
with open("text.txt", "r", encoding="latin-1") as file:
    content = file.read()

# Writing with encoding
with open("text.txt", "w", encoding="utf-8") as file:
    file.write("Hello, World! 你好")

📊 File Modes

ModePurposeData Type
`"r"`Read textstr
`"w"`Write textstr
`"rb"`Read binarybytes
`"wb"`Write binarybytes

🔑 Key Takeaways

  • ✅ Use `"rb"`/`"wb"` for binary files
  • ✅ Binary reading returns `bytes` objects
  • ✅ Text files have encoding (usually UTF-8)
  • ✅ Binary mode preserves data exactly
  • ✅ Use for images, PDFs, any non-text file

Ready to practice? Challenges | Quiz


Resources

Python Docs

Ojasa Mirai

Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.

Learn Deep • Build Real • Verify Skills • Launch Forward

Courses

PythonFastapiReactJSCloud

© 2026 Ojasa Mirai. All rights reserved.

TwitterGitHubLinkedIn