Lesson 6.2: Working with Different File Modes
Introduction:
Python provides multiple file modes that determine how a file is opened and manipulated. Choosing the correct mode is crucial for safe data operations, preventing accidental overwrites, and handling binary or text files appropriately.
1. Text File Modes:
| Mode | Description | Example Use |
|---|---|---|
'r' |
Read-only (default) | Open a file to read content |
'w' |
Write (overwrites existing content) | Save new data or overwrite old data |
'a' |
Append (add at end) | Add new information without deleting existing data |
'r+' |
Read and write | Read existing content and update the file |
Example – Reading and Writing:
2. Binary File Modes:
| Mode | Description | Example Use |
|---|---|---|
'rb' |
Read binary | Reading images, PDFs, or audio files |
'wb' |
Write binary | Saving binary data |
'ab' |
Append binary | Add binary data without overwriting |
'rb+' |
Read and write binary | Modify binary files |
Example – Binary File:
3. Best Practices:
-
Always use
withstatement to ensure files are closed properly -
Use
'a'mode to prevent accidental data loss -
Use binary modes for non-text files like images, videos, or PDFs
-
Double-check mode before writing to avoid overwriting important files
Learning Outcome of This Lesson:
-
Understand all text and binary file modes in Python
-
Apply the correct mode for reading, writing, and appending
-
Safely handle both text and binary files
-
Prevent data loss through careful mode selection
