appzasGamesToolsDevLearnCheat sheetsQuick calcsConvertersReferenceNetworkTimeCalculatorsCompareLLM prices

Files, errors and modules

Lesson 4 of 410 minBeginner

Read and write files, handle errors and use the standard library.

Read and write files

with open("notes.txt", "w", encoding="utf-8") as f:
    f.write("first line\n")

with open("notes.txt", encoding="utf-8") as f:
    for line in f:
        print(line.strip())

The with block closes the file for you, even if an error happens. Modes: "r" read, "w" write (erases the file first!), "a" append.

Handling errors

try:
    n = int(input("Number: "))
except ValueError:
    print("That was not a number")
else:
    print(n * 2)

Modules

import json, random
from datetime import date

data = json.loads('{"a": 1}')
print(data["a"])
print(random.randint(1, 6))
print(date.today())

Python ships with a large standard library: json, csv, datetime, pathlib, urllib and more. Install third-party packages with pip install requests inside a virtual environment.

python3 -m venv .venv
source .venv/bin/activate
pip install requests

CarefulCatch specific errors such as ValueError. A bare except: hides real bugs.

Test yourself

Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.

1. What does opening a file with mode "w" do to an existing file?
2. Why use a with block for files?
Hintpython3 -m venv and the folder name.
4. Which error does int("abc") raise?

Key terms