Files & Errors
Read and write files, and handle errors so your program does not crash.
What you will learn
- Read and write files
- Handle errors with try/except
Read & write files
Programs often need to save information so it survives after they close, and read it back later. Python does this with open(). The with keyword is the safe way to use it — it automatically closes the file for you when the block ends, even if something goes wrong.
# write
with open("note.txt", "w") as f:
f.write("Hello, file!")
# read
with open("note.txt") as f:
print(f.read())There are two stages here — writing, then reading:
open("note.txt", "w")opens (or creates) the file in write mode — the"w".as fgives us a handle namedfto work with.f.write("Hello, file!")puts that text into the file. When thewithblock ends, Python saves and closes the file automatically.open("note.txt")opens the same file again — with no mode given it defaults to read mode.f.read()reads the whole contents back as text, andprintshows it on screen.
Note: Output:
Hello, file!
A file called note.txt now exists on your computer containing that text.
Watch out: Write mode "w" overwrites the whole file every time. To add to the end without erasing what is there, use append mode: open("note.txt", "a").
Handle errors
Some code can fail at runtime — for instance if the user types letters when you expected a number. Wrap risky code in try / except so an error shows a friendly message instead of crashing the whole program.
try:
number = int(input("Enter a number: "))
print("Double is", number * 2)
except ValueError:
print("That was not a number!")Python runs the try block first. If everything works — the user types a real number — it converts the text, doubles it, and prints the answer; the except block is skipped. But if int() fails because the input was not a number, Python raises a ValueError, jumps straight to the matching except ValueError: block, and prints the friendly message instead of crashing.
Note: Output (if the user types "7"): Enter a number: 7 Double is 14 Output (if the user types "hello"): Enter a number: hello That was not a number!
Q. Which block runs if the code in try fails?
✍️ Practice
- Write text to a file, then read it back.
- Use try/except to handle a bad number input.
🏠 Homework
- Build a note saver: ask for text and append it to a file.