In this lesson, you will learn how to distinguish between text and binary file modes so that your programs process data in the correct format without corruption.
Understanding the Stream Difference
When you open a file in Python, you must decide whether to treat the data as a stream of text or a stream of raw bytes. This choice determines how Python interacts with the underlying operating system and how it translates data for your application.
Text Mode (The Default)
Text mode is used for human-readable files like .txt, .csv, or .json. When you open a file in text mode (e.g., open('file.txt', 'r')), Python assumes the contents represent characters. It automatically handles encoding and decoding, converting the file’s raw bits into Python str objects based on a specific character encoding (typically utf-8).
Binary Mode
Binary mode is used for files that aren't meant to be read as text, such as images (.png), audio (.mp3), or compiled executables. By adding the b flag to the mode (e.g., open('image.jpg', 'rb')), you instruct Python to bypass all encoding logic. Instead of returning str objects, Python returns bytes objects—a sequence of raw integers representing the exact data stored on the disk.
The Critical Distinction
If you try to read a binary file in text mode, Python will attempt to decode the raw bytes into a str. If the binary data contains byte sequences that don't map to valid characters, Python will raise a UnicodeDecodeError. Conversely, if you read a text file in binary mode, you lose the ability to easily manipulate characters because you are forced to work with individual bytes, which may not align with your intended character encoding.
# Working with text: Python handles encoding/decoding automatically
with open('notes.txt', 'w', encoding='utf-8') as f:
f.write("Hello, World!")
# Working with binary: We deal with raw bytes directly
with open('data.bin', 'wb') as f:
f.write(b'\x00\x0F\x87')
Key Takeaway: Use text mode for human-readable strings to automate encoding, and use binary mode for non-text files to access raw data without interference.