Welcome back to 100 Days of Python!
In the last few days, we explored reading and writing files.
Today, we’ll dig deeper into file modes (how Python opens files) and error handling to make your file operations safe and reliable.
📄 1. File Modes Overview
When you use open()
in Python, you specify a mode to tell Python how to open the file.
Mode | Meaning | Creates File? | Overwrites? |
---|---|---|---|
"r" |
Read (default) | ❌ | ❌ |
"w" |
Write | ✅ | ✅ |
"a" |
Append | ✅ | ❌ |
"x" |
Create (fails if exists) | ✅ | ❌ |
"b" |
Binary mode | — | — |
"t" |
Text mode (default) | — | — |
"+" |
Read and write | — | — |
Examples:
# Read mode
with open("data.txt", "r") as f:
content = f.read()
# Write mode
with open("output.txt", "w") as f:
f.write("Overwrites content!")
# Append mode
with open("output.txt", "a") as f:
f.write("\nNew line added.")
# Binary mode
with open("image.png", "rb") as f:
binary_data = f.read()
🛡️ 2. Error Handling in File Operations
File operations can fail for many reasons:
- File doesn’t exist
- No permission to read/write
- Disk full or path invalid
To prevent crashes, use try-except blocks:
try:
with open("data.txt", "r") as f:
content = f.read()
except FileNotFoundError:
print("File not found! Please check the filename.")
except PermissionError:
print("You don't have permission to access this file.")
except Exception as e:
print(f"Unexpected error: {e}")
⚡ 3. Combining Modes and Exception Handling
Example: Reading and Writing Safely
filename = "notes.txt"
try:
with open(filename, "a+") as f: # Append & read
f.write("New note added.\n")
f.seek(0) # Go to start to read file
print(f.read())
except IOError as e:
print(f"I/O error occurred: {e}")
🧠 4. Tips for Working with File Modes
-
Default mode is
"r"
(read text). - Use
"b"
for binary files like images or PDFs. -
"a"
is safer than"w"
if you don’t want to lose existing data. - Always handle errors to prevent program crashes.
- Use
with open()
to automatically close files.
🛠️ Practice Challenge
- Write a script that:
- Opens a file in
"x"
mode and writes"First entry"
. - If the file already exists, appends
"Another entry"
instead. - Handles all file-related errors gracefully.
Top comments (0)