Python Mastery – From Basics to Brilliance / File Handling

Using with open()

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

With with

You must call file.close() yourself

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

"r"

Read only

Reading saved data

"w"

Write (overwrites!)

Writing fresh data

"a"

Append to file

Adding data to end

"x"

Create new file

Safely create if not exists

"b"

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

"r"

Save user input (overwrite)

"w"

Add new logs/data

"a"

Create only if file doesn’t exist

"x"

Work with images/media

"rb" / "wb"


✅ Final Tip:

Always use with open() — it’s the safe, clean, and professional way to handle files in Python.