Files and Errors in Python: with open() and try/except
Read and write text files safely using with open(), and catch expected errors with try/except without swallowing real bugs.
You'll learn how to read, write, and append files with with open() so they always close cleanly, and how try / except handles missing files or bad user input without crashing your script. Assumes basic Python variables and loops.
1. Saving data past the end of your script
Variables live in memory and evaporate the instant your script exits. Files let you save data on disk.
Always open files with a with block—that guarantees Python closes the file automatically when the block ends, even if an error blows up halfway through:
with open("log.txt", "w", encoding="utf-8") as f:
f.write("Monday: optimistic\n")
f.write("Tuesday: tired\n")
with open("log.txt", "r", encoding="utf-8") as f:
for line in f:
print(line.strip())Monday: optimistic
Tuesday: tiredKnow the three modes:
"r"— read (default; crashes if the file doesn't exist)."w"— write (erases the file first if it already exists!)."a"— append (adds to the end without erasing).
2. Catching expected crashes with try / except
If you try to open a file that isn't there—or convert "banana" with int("banana")—Python raises an exception and stops the program.
try / except lets you catch specific expected failures and recover politely:
try:
with open("missing.txt", "r", encoding="utf-8") as f:
print(f.read())
except FileNotFoundError:
print("No missing.txt yet—creating a fresh one.")No missing.txt yet—creating a fresh one.Never write a bare except: with no error name. A bare except: catches everything, including typos in your own code and Ctrl+C when you're trying to quit! Always name the exact exception you expect (FileNotFoundError, ValueError, ZeroDivisionError).
Wrap int("abc") in try: ... except ValueError: print("Not a number") and run it to confirm it handles the bad input cleanly.
Common mistakes
| Error / Bug | What it means | Fix |
|---|---|---|
| Existing file wiped empty | Opened it with "w" instead of "a" or "r" | Use "a" to add lines, "r" to read |
FileNotFoundError | File isn't in the folder you ran python3 from | Check the path with pathlib.Path("file").resolve() |
| Bugs silently ignored | Used except: pass | Catch specific exceptions and log or handle them |
Practice
- Which file mode adds new text to the end of
log.txtwithout deleting Monday's entry?
Answer: "a" (append mode).
What you learned
- Always use
with open(path, mode, encoding="utf-8")so files close automatically. "w"overwrites;"a"appends;"r"reads.- Catch specific exceptions (
except ValueError:) instead of a bareexcept:.