جواب «(Harder) Command History» چالش 6 از جلسهی 23
سؤال
(سختتر) همان دستیارِ count/list/help/ناشناس (پوشه در شروع دو فایل notes.txt و todo.txt دارد)، بهعلاوه: هر دستوری که وارد میشود (حتی ناشناس، ولی نه quit) به آخر history.log اضافه شود، و دستور history همهی خطهای آن فایل را با شماره چاپ کند: 1 count، 2 list، ... (خود history هم قبل از چاپ ثبت میشود).
راهنما
اول هر دور (بعد از چک quit): with open("history.log", "a") as f: f.write(command + "\n"). برای history: enumerate(lines, 1).
یک جواب درست
import os
for name in ["notes.txt", "todo.txt"]:
with open(name, "w") as f:
f.write("")
def do_count():
print(f"{len(os.listdir('.'))} files")
def do_list():
for name in sorted(os.listdir(".")):
print(name)
def do_history():
with open("history.log") as f:
lines = f.read().splitlines()
for i, line in enumerate(lines, 1):
print(f"{i} {line}")
commands = {"count": do_count, "list": do_list, "history": do_history}
while True:
command = input()
if command == "quit":
break
with open("history.log", "a") as f:
f.write(command + "\n")
if command == "help":
print("commands: " + ", ".join(sorted(commands)))
elif command not in commands:
print(f"Unknown command: {command}")
else:
commands[command]()
اول خودت امتحان کن؛ جوابهای دیگر هم قبول است. برگرد و خودت حلش کن