Menu
Courses / python basic / Files & Exceptions

Files & Exceptions

09 / 10 Part of python basic




 

    📁 Topic 09 · Robustness
 

 


    Files & Exceptions
 


 


    Read and write files safely, handle errors gracefully with try/except, and create custom exceptions for cleaner, production-ready code.
 


 

    ⏱ ~45 min
    🟡 Intermediate
    🛡️ Reliability
 


 
 

   

     
     

Reading & Writing Files


   

   

Always use the with statement — it guarantees the file is closed even if an error occurs mid-operation.


   

     

        files.py
     

     
# Write to a file
with open("data.txt", "w") as f:
    f.write("Hello, file!\n")
    f.write("Second line\n")

# Read entire file at once
with open("data.txt", "r") as f:
    content = f.read()

# Read line by line (memory-efficient)
with open("data.txt") as f:
    for line in f:
        print(line.strip())

   

   

      📌 File modes
     

"r" read (default) · "w" write (overwrites) · "a" append · "b" binary · "x" exclusive create (fails if exists)


   

 


 
 

   

     
     

try / except / finally


   

   

Wrap risky code in a try block and handle specific exceptions so the program stays running.


   

     

        exceptions.py
     

     
try:
    num    = int(input("Enter number: "))
    result = 100 / num
    print(f"Result: {result}")

except ValueError:
    print("That wasn't a valid number!")

except ZeroDivisionError:
    print("Cannot divide by zero!")

except Exception as e:
    print(f"Unexpected error: {e}")

else:
    print("Success — no exceptions!")

finally:
    print("This always runs — great for cleanup")

   

 


 
 

   

     
     

Custom Exceptions


   

   

Inherit from Exception to create domain-specific errors with meaningful names.


   

     

        custom_exc.py
     

     
class InsufficientFundsError(Exception):
    def __init__(self, amount, balance):
        super().__init__(f"Need {amount}, have {balance}")

def withdraw(balance, amount):
    if amount > balance:
        raise InsufficientFundsError(amount, balance)
    return balance - amount

try:
    withdraw(50, 100)
except InsufficientFundsError as e:
    print(e)  # Need 100, have 50

   

 


 
 

   

     
     

Working with JSON


   

   

Python's built-in json module makes reading and writing structured data trivial.


   

     

        json_files.py
     

     
import json

data = {"name": "Alice", "scores": [95, 87, 92]}

# Write JSON
with open("data.json", "w") as f:
    json.dump(data, f, indent=2)

# Read JSON
with open("data.json") as f:
    loaded = json.load(f)

print(loaded["name"])   # Alice