In this lesson, you will learn how to read and write non-textual data, such as images or serialized objects, by utilizing binary-mode file access.
Understanding Binary Mode
When you open a file in Python, the default mode assumes you are working with text (strings). However, files like JPEGs, PDFs, or compiled programs consist of raw bytes rather than characters. To handle these, we append a b to the file mode—using 'rb' for "read binary" and 'wb' for "write binary."
When you read a file in binary mode, Python returns a bytes object instead of a string. This is crucial because binary data doesn't follow text encodings like UTF-8.
Practical Example: Copying an Image
Imagine you want to back up an image file. Because we are dealing with raw data, we must ensure we handle the stream correctly.
# Reading from a source and writing to a destination
try:
with open('photo.jpg', 'rb') as source:
data = source.read() # Reads the entire file as a byte stream
with open('photo_backup.jpg', 'wb') as destination:
destination.write(data)
except IOError as e:
print(f"An error occurred while accessing the file: {e}")
Buffering and Large Files
For very large files, reading the entire contents into memory with read() can crash your program. Instead, you can process the file in chunks to manage memory efficiently. By specifying a buffer size, you can stream the data in smaller segments:
with open('large_video.mp4', 'rb') as source:
with open('copy.mp4', 'wb') as destination:
while True:
chunk = source.read(1024) # Read 1KB at a time
if not chunk:
break
destination.write(chunk)
By using binary mode, you bypass text-processing overhead and character encoding issues, allowing Python to treat files as literal sequences of bytes. This is the foundation for working with any file that isn't plain text.
Key Takeaway: Always use 'rb' or 'wb' modes when handling non-textual files to ensure data integrity, and process large files in chunks to keep your memory usage stable.