Tutorials Courses Interview Prep (100 Q&A) AI Tools (50) Developer Tools (50) Tracks Pricing Plans Blog & Articles Contact Us
Python 3 Fundamentals & OOP 16 mins read Free Lesson

File Handling, Context Managers (with) & Exceptions

Safely open files with the with statement and handle errors using try-except-finally blocks.

File I/O & Exception Handling

# Context Manager automatically closes file handle upon exit
try:
    with open("config.json", "r", encoding="utf-8") as f:
        data = f.read()
        print("Config loaded successfully!")
except FileNotFoundError:
    print("Warning: config.json not found, using default values.")
except Exception as e:
    print(f"Unexpected error: {e}")