Red Hat – OOP & File Handling
advanced35 XP

Files & Error Handling

Read and write files, handle errors gracefully with try/except

Files & Errors

Python
with open("scores.txt", "w") as f:
    f.write("Alex: 100\n")

with open("scores.txt", "r") as f:
    print(f.read())

try/except

Python
try:
    age = int(input("Your age: "))
    print(f"In 10 years: {age + 10}")
except ValueError:
    print("That's not a valid number!")
finally:
    print("Done!")
⌨️

Type it yourself

Don't just read it — type the example from above into the box, press Run ▶, and watch what happens. Typing it yourself is how it really sticks! Stuck? Tap Show example.

Python · Playground
Output
Press ▶ Run to see your code come to life…

Quick check

01/2

Which file mode adds content WITHOUT erasing existing content?