56 — Log: an event record
The diary in guide 35 writes one file per day. A log is the opposite: one growing file with a new line for every event, showing when things happened.
Steps
Ask
datetimefor now and shape it as text.datetime.now()is this moment;strftime(guide 24) formats it —%Yyear,%mmonth,%dday,%Hhour,%Mminute:
run it →from datetime import datetime now = datetime.now() stamp = now.strftime("%Y-%m-%d %H:%M") show stampfile_writefrom guide 13 replaces the whole file, so appending means read the old log, add one line, write it all back:
run it →use file latest log = file_read("log.txt") file_write("log.txt", log + stamp + " - program started\n")Python's
open(path, "a")appends in one call — theameans append — but the read-then-write way also lets the program read the log back for a menu.The full logger appends a dated line on every
add. The first run must not fail whenlog.txtdoes not exist, soos.path.existsstarts empty. Save it aslog.nme:
run it →# log.nme — a small event logger. # Run: nme r log use file latest from datetime import datetime import os if os.path.exists("log.txt"): log = file_read("log.txt") else: log = "" while True: ask choice, "(add, show, quit) " if choice == "add": ask event, "what happened? " stamp = datetime.now().strftime("%Y-%m-%d %H:%M") log = log + stamp + " - " + event + "\n" file_write("log.txt", log) show "saved: " + stamp + " - " + event elif choice == "show": show "log.txt has " + str(len(log.splitlines())) + " line(s):" for line in log.splitlines(): show line else: show "bye" breakRun it twice, adding a different event each time — the second run shows the first event still there, the log growing across runs:
printf 'add\nwater the plants\nshow\nquit\n' | nme r log printf 'add\ncall mom\nshow\nquit\n' | nme r log(add, show, quit) what happened? saved: 2026-08-11 14:05 - water the plants (add, show, quit) log.txt has 1 line(s): 2026-08-11 14:05 - water the plants (add, show, quit) bye (add, show, quit) what happened? saved: 2026-08-11 14:05 - call mom (add, show, quit) log.txt has 2 line(s): 2026-08-11 14:05 - water the plants 2026-08-11 14:05 - call mom (add, show, quit) byeThe timestamps are real — run it yourself and
log.txtrecords the actual minute of eachadd.
Try it yourself
Count events per day: change the timestamp to strftime("%Y-%m-%d"), then use
the dict counting from guide 36 for how many lines share
each date.
What you learned
datetime.now().strftime(format)shapes the current moment as text.- Appending is read + one new line +
file_write, becausefile_writereplaces the whole file. open(path, "a")appends directly;withcloses the file.os.path.existslets the first run start with an empty log.