
Python
Learn to handle binary files like images, and understand text encoding.
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 bytesUse `"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# 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 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! 你好")| Mode | Purpose | Data Type |
|---|---|---|
| `"r"` | Read text | str |
| `"w"` | Write text | str |
| `"rb"` | Read binary | bytes |
| `"wb"` | Write binary | bytes |
Ready to practice? Challenges | Quiz
Resources
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