with open("example.txt", "r") as file:
content = file.read()
print(content)🧠 What’s Happening?
"example.txt"is opened for reading ("r"mode).Inside the block, you can safely read/write.
No need to close manually — Python closes it automatically once the block finishes.
🛡️ Why It’s Safer?
Without | With |
|---|---|
You must call | Python does it for you |
May forget to close (causing bugs) | No chance of forgetting |
Less clean code | More readable and cleaner |
🔹 File Modes Table — Made Easy
Mode | Meaning | Example Use |
|---|---|---|
| Read only | Reading saved data |
| Write (overwrites!) | Writing fresh data |
| Append to file | Adding data to end |
| Create new file | Safely create if not exists |
| Binary mode | For images, PDFs, etc. |
📌 Combine Modes:
"rb"→ read a file as binary"wb"→ write binary (e.g., save images or PDFs)
🧪 Real-World Examples
# 1. Write (overwrites if file exists)
with open("notes.txt", "w") as f:
f.write("Python is powerful!")
# 2. Append (adds to existing content)
with open("notes.txt", "a") as f:
f.write("\\nAnd it's beginner-friendly too!")
# 3. Read file
with open("notes.txt", "r") as f:
print(f.read())Python is powerful!
And it's beginner-friendly too!💡 When to Use Which Mode?
Task | Mode |
|---|---|
View existing file |
|
Save user input (overwrite) |
|
Add new logs/data |
|
Create only if file doesn’t exist |
|
Work with images/media |
|
✅ Final Tip:
Always use with open() — it’s the safe, clean, and professional way to handle files in Python.