Working with DataExtra· 30 min read

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.

with open(...) safely handles files
# 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:

  1. open("note.txt", "w") opens (or creates) the file in write mode — the "w". as f gives us a handle named f to work with.
  2. f.write("Hello, file!") puts that text into the file. When the with block ends, Python saves and closes the file automatically.
  3. open("note.txt") opens the same file again — with no mode given it defaults to read mode.
  4. f.read() reads the whole contents back as text, and print shows 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 / except catches errors
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?

Answer: Python uses except to handle errors raised in the try block.

✍️ Practice

  1. Write text to a file, then read it back.
  2. Use try/except to handle a bad number input.

🏠 Homework

  1. Build a note saver: ask for text and append it to a file.
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →