#!/usr/bin/python3 import csv import os from datetime import datetime, timedelta from typing import Callable backup_loc = os.path.expanduser("~/backup/openflights") now = datetime.now() since_date = now - timedelta(days=365 * 5) airlines = { "British Airways": "BA", "Iberia Airlines": "IB", "Qatar Airways": "QR", "Ryanair": "FR", "easyJet": "U2", "SAS": "SK", } Flight = dict[str, str] Flights = list[tuple[datetime, Flight]] def get_most_recent(loc: str, pred: Callable[[str], bool] | None = None) -> str | None: """Get the most recent file in a directory.""" files = [f for f in os.listdir(loc) if pred is None or pred(f)] return os.path.join(loc, max(files)) if files else None def format_row(dt: datetime, f: Flight) -> str: """Format flight.""" d = dt.strftime("%a, %d %b %Y") days = (dt - now).days if days == 0 or days == -1: delta = "today" elif days < 0: delta = f"{-days:>3d} days ago" else: delta = f"{days:>3d} days" airline = f["Airline"] if len(airline) > 15: airline = "".join(t[0] for t in airline.split()) flight_number = f["Flight_Number"] if flight_number.isdigit() and airline in airlines: flight_number = airlines[airline] + flight_number return ( ("*" if delta == "today" else " ") + f' {d} {delta:>13s} {f["From"]:4s} -> {f["To"]:4s} ' + f'{airline:>15s} {flight_number:<7s} {f["Class"]} ' + f'{f["Seat"]:>4s} ' + f'{f["Registration"]:6s} ' + f'{f["Plane"]} ' ) def read_flights(filename: str) -> Flights: """Read flights from CSV.""" reader = csv.DictReader(open(filename)) flights = [] for row in reader: d = row.pop("\ufeffDate") if len(d) > 10: d = datetime.strptime(d, "%Y-%m-%d %H:%M:%S") else: d = datetime.strptime(d, "%Y-%m-%d") row = {k: v for k, v in row.items() if not k.endswith("OID")} # for key in "Trip", "Seat", "Seat_Type", "Class", "Reason", "Note": # row.pop(key) if d < since_date: continue flights.append((d, row)) flights.sort() return flights def show_flights(flights: Flights) -> None: """Show list of flights.""" for d, row in flights: print(format_row(d, row)) if __name__ == "__main__": filename = get_most_recent(backup_loc, lambda f: f.endswith(".csv")) assert filename flights = read_flights(filename) show_flights(flights)