Programming

The standard library

sys, os, pathlib, datetime, random and logging.

All lessons · Python lessons: learn from scratch

What the standard library is

Hundreds of ready modules ship with Python. Before writing something yourself, check whether a ready solution exists; it saves time and is more reliable.

sys, os and pathlib

sys reports about the interpreter (sys.version, sys.argv). os talks to the operating system. Writing file paths with pathlib is cleaner and works the same everywhere.

import sys, os
from pathlib import Path

print(sys.version_info[:2])
print(os.getcwd())
for p in Path(".").glob("*.py"):
    print(p.name, p.stat().st_size)

datetime, random and logging

datetime handles dates and times, random makes random choices, and logging records what the program does to a file or the screen; unlike print it has levels (DEBUG, INFO, WARNING, ERROR).

import logging, random
from datetime import date, timedelta

logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
deadline = date.today() + timedelta(days=14)
logging.info("deadline is %s", deadline)
print(random.choice(["red", "green", "blue"]))

Author: Nibras Code