Files, errors and modules
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 requestsCarefulCatch specific errors such as ValueError. A bare except: hides real bugs.
Try it
Test yourself
Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.