Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

PY
Python
0/14 completed
Beginner
Hello PythonVariables and typesWorking with stringsConditions and loopsFunctions
Intermediate
Lists, tuples, dicts and setsFiles and exceptionsModules and the standard library
Advanced
Classes and OOPIterators and generatorsDecorators and context managers
Pro
Async PythonTesting and type hintsVirtual environments, packages and real projects
Tracks / Python / Intermediate

Files and exceptions

Programs need to save and load data, and they need to cope with things going wrong: a missing file, bad user input, a network error. This lesson covers both.

The editors here have their own little in-memory file system, so you can create and read files safely. They disappear when the run ends.

Writing and reading text files

Python · editable

The with statement closes the file automatically, even if an error happens. Always use it.

Reading line by line

Python · editable

Looping over the file reads one line at a time, so it works even for huge files.

Mode Meaning
"r" Read (default). Error if the file doesn't exist.
"w" Write. Creates the file, or erases it first.
"a" Append to the end.
"x" Create; error if it already exists.
"b" Add for binary files: "rb", "wb" (images, PDFs)

Specify encoding="utf-8" on real projects so accented letters and emoji behave the same on every computer.

Paths with pathlib

The modern way to work with files and folders is pathlib:

Python · editable

CSV and JSON

Two formats you'll meet constantly. Both have built-in modules:

Python · editable
Python · editable

Exceptions

When something goes wrong, Python raises an exception. If nothing handles it, the program stops with a traceback:

Python · editable

try / except

Handle errors you expect, and decide what should happen instead:

Python · editable

else and finally

Python · editable

Common exceptions

Exception Typical cause
ValueError Right type, wrong value: int("abc")
TypeError Wrong type: "a" + 1
KeyError Missing dict key
IndexError List index out of range
FileNotFoundError Opening a file that isn't there
ZeroDivisionError Dividing by zero
AttributeError None.upper(), a typo in a method name

Raising your own

Python · editable

You can also define custom exception classes (you'll learn classes soon):

Python · editable

Good practice

  • Catch specific exceptions. A bare except: also hides bugs (and even Ctrl+C).
  • Keep the try block small: only the lines that can actually fail.
  • Don't silently ignore errors. At least log them.
  • "It's easier to ask forgiveness than permission" (EAFP): in Python, trying and catching is often cleaner than checking everything first.

Practice

  1. Write a list of 5 shopping items to shopping.txt, then read it back and print it numbered.
  2. Write a function safe_int(text, default=0) that returns the number, or the default if conversion fails.
  3. Save a dict of three students and their marks to marks.json, load it, and print the average.
Python · editable
✎ Check your understanding

1.Why use with open(...) as f:?

2.What does opening a file with mode "w" do to an existing file?

3.When does the finally block run?

← Lists, tuples, dicts and sets