נבנה על ידיBuilt by Ariel Yohimovich

PythonPython
28
חלקPart 5: בונים דבריםBuilding things כ-3 שעות (כולל הפסקה)About 3 hours (with a break)

אוטומציה של משימותAutomating tasks

קבצים ותיקיות בכמויות, תזמון, ודוחות אוטומטיים.

Files and folders in bulk, scheduling, and automatic reports.

נסו לפתור לבד לפני שמציצים. בנגן: חיצים במקלדת או הכפתורים. כל צעד מראה איפה (קובץ ושורה), מה כותבים ולמה.Try on your own before peeking. In the player use the arrow keys or the buttons. Each step shows where (file and line), what to write, and why.
תרגילExercise 1

ספירה לפי סוגCounting by type

תזכורת: מה ביקשוReminder: the task

הקוד יוצר תיקייה עם קבצים. כתבו count_kinds(folder) שמחזירה מילון סיומת (באותיות קטנות, בלי נקודה) → כמות, וקובץ בלי סיומת נספר תחת "none".

The code creates a folder of files. Write count_kinds(folder) returning a dict extension (lowercase, no dot) → count, with extensionless files counted under "none".

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
main.py
from pathlib import Path

box = Path("box")
box.mkdir(exist_ok=True)
for n in ["a.TXT", "b.txt", "c.png", "README", "d.Png"]:
    (box / n).write_text("x")
(box / "sub").mkdir(exist_ok=True)

def count_kinds(folder):
    counts = {}
    for p in Path(folder).iterdir():
        if p.is_file():
            k = p.suffix.lower().lstrip(".") or "none"
            counts[k] = counts.get(k, 0) + 1
    return counts

print(dict(sorted(count_kinds(box).items())))
פלטOutput
{'none': 1, 'png': 2, 'txt': 2}

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 2

סידור עם dry runTidying with a dry run

תזכורת: מה ביקשוReminder: the task

כתבו plan(folder, rules) שמחזירה רשימת זוגות (שם קובץ, תיקיית יעד) בלי להזיז כלום, ו-apply(folder, rules) שמבצעת את התוכנית ומחזירה כמה קבצים הוזזו. rules הוא מילון סיומת → תיקייה, וכל השאר הולך ל-other.

Write plan(folder, rules) returning pairs (file name, target folder) without moving anything, and apply(folder, rules) carrying out the plan and returning how many files moved. rules is a dict extension → folder, and anything else goes to other.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
main.py
import shutil
from pathlib import Path

def plan(folder, rules):
    folder = Path(folder)
    return [(f.name, rules.get(f.suffix.lower(), "other")) for f in sorted(folder.iterdir()) if f.is_file()]

def apply(folder, rules):
    folder = Path(folder)
    steps = plan(folder, rules)
    for name, target in steps:
        (folder / target).mkdir(exist_ok=True)
        shutil.move(str(folder / name), str(folder / target / name))
    return len(steps)

d = Path("dl")
d.mkdir(exist_ok=True)
for n in ["a.pdf", "b.mp3", "c.PDF"]:
    (d / n).write_text("x")
rules = {".pdf": "docs", ".jpg": "images"}
print(plan(d, rules))
print(apply(d, rules), sorted(str(p.relative_to(d)) for p in d.rglob("*.*")))
פלטOutput
[('a.pdf', 'docs'), ('b.mp3', 'other'), ('c.PDF', 'docs')]
3 ['docs/a.pdf', 'docs/c.PDF', 'other/b.mp3']

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 3

מספור תמונותNumbering photos

תזכורת: מה ביקשוReminder: the task

כתבו new_names(names, prefix) שמקבלת רשימת שמות קבצים, ממיינת אותם, ומחזירה מילון שם ישן → שם חדש בצורה prefix-001.ext (סיומת באותיות קטנות, ו-.jpeg הופך ל-.jpg). בלי לגעת בקבצים.

Write new_names(names, prefix) that takes file names, sorts them, and returns a dict old name → new name in the form prefix-001.ext (lowercase extension, .jpeg becomes .jpg). Without touching files.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
main.py
from pathlib import Path

def new_names(names, prefix):
    out = {}
    for i, n in enumerate(sorted(names), 1):
        ext = Path(n).suffix.lower()
        if ext == ".jpeg":
            ext = ".jpg"
        out[n] = f"{prefix}-{i:03}{ext}"
    return out

print(new_names(["IMG_9.JPEG", "IMG_10.png", "IMG_1.jpg"], "trip"))
פלטOutput
{'IMG_1.jpg': 'trip-001.jpg', 'IMG_10.png': 'trip-002.png', 'IMG_9.JPEG': 'trip-003.jpg'}

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 4

שמירה רק של האחרוניםKeeping only the latest

תזכורת: מה ביקשוReminder: the task

כתבו prune(folder, keep) שמוחקת את קבצי backup-YYYY-MM-DD.zip הישנים ומשאירה רק את keep החדשים ביותר (לפי התאריך בשם). מחזירה רשימת שמות שנמחקו, ממוינת. קבצים אחרים בתיקייה לא נוגעים.

Write prune(folder, keep) deleting old backup-YYYY-MM-DD.zip files and keeping only the keep newest (by the date in the name). Return a sorted list of deleted names. Other files in the folder are untouched.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
main.py
from pathlib import Path

def prune(folder, keep):
    files = sorted(Path(folder).glob("backup-*.zip"))
    old = files[:-keep] if keep else files
    for f in old:
        f.unlink()
    return [f.name for f in old]

b = Path("bk")
b.mkdir(exist_ok=True)
for d in ["2026-03-01", "2026-02-27", "2026-03-03", "2026-03-02"]:
    (b / f"backup-{d}.zip").write_text("z")
(b / "notes.txt").write_text("keep me")
print(prune(b, 2))
print(sorted(p.name for p in b.iterdir()))
פלטOutput
['backup-2026-02-27.zip', 'backup-2026-03-01.zip']
['backup-2026-03-02.zip', 'backup-2026-03-03.zip', 'notes.txt']

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 5

מדף, צעד 28: גיבוי ודוח שבועיShelf, step 28: a backup and a weekly report

תזכורת: מה ביקשוReminder: the task

כתבו daily(folder, day) שיוצרת ZIP של קבצי ה-JSON בתיקייה (folder/backups/shelf-<day>.zip, רק *.json), ו-weekly(log, day) שמקבלת רשימת {day, pages} ומחזירה דוח טקסט: שורה ראשונה Week ending <day>, אחריה Pages: N ו-Best day: <day> (N).

Write daily(folder, day) creating a ZIP of the folder's JSON files (folder/backups/shelf-<day>.zip, only *.json), and weekly(log, day) taking a list of {day, pages} and returning a text report: first line Week ending <day>, then Pages: N and Best day: <day> (N).

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
automate.py
import zipfile
from pathlib import Path

def daily(folder, day):
    folder = Path(folder)
    out = folder / "backups" / f"shelf-{day}.zip"
    out.parent.mkdir(exist_ok=True)
    with zipfile.ZipFile(out, "w") as z:
        for f in sorted(folder.glob("*.json")):
            z.write(f, arcname=f.name)
    return out

def weekly(log, day):
    best = max(log, key=lambda e: e["pages"])
    return "\n".join([f"Week ending {day}", f"Pages: {sum(e['pages'] for e in log)}", f"Best day: {best['day']} ({best['pages']})"])

proj = Path("shelfproj")
proj.mkdir(exist_ok=True)
(proj / "shelf.json").write_text("[]")
(proj / "goals.json").write_text("{}")
(proj / "notes.txt").write_text("skip")
z = daily(proj, "2026-03-07")
print(z.name, zipfile.ZipFile(z).namelist())
print(weekly([{"day": "Mon", "pages": 40}, {"day": "Wed", "pages": 75}, {"day": "Fri", "pages": 30}], "2026-03-07"))
פלטOutput
shelf-2026-03-07.zip ['goals.json', 'shelf.json']
Week ending 2026-03-07
Pages: 145
Best day: Wed (75)

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

אתגרChallenge 1

מוצא כפילויותA duplicate finder

תזכורת: מה ביקשוReminder: the task

כתבו duplicates(folder) שמוצאת קבצים עם תוכן זהה (גם בתת-תיקיות, גם בשמות שונים) בעזרת hash (hashlib.sha256 על התוכן). מחזירה רשימת קבוצות: כל קבוצה רשימה ממוינת של נתיבים יחסיים (כמחרוזות עם /), רק קבוצות של 2 ומעלה, והקבוצות ממוינות.

Write duplicates(folder) finding files with identical content (in subfolders too, under different names) using a hash (hashlib.sha256 of the content). Return a list of groups: each a sorted list of relative paths (as strings with /), only groups of 2+, and the groups sorted.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
main.py
import hashlib
from pathlib import Path

def duplicates(folder):
    folder = Path(folder)
    by_hash = {}
    for p in folder.rglob("*"):
        if p.is_file():
            h = hashlib.sha256(p.read_bytes()).hexdigest()
            by_hash.setdefault(h, []).append(p.relative_to(folder).as_posix())
    return sorted(sorted(g) for g in by_hash.values() if len(g) > 1)

root = Path("photos")
(root / "2025").mkdir(parents=True, exist_ok=True)
(root / "a.jpg").write_text("sunset")
(root / "2025" / "copy of a.jpg").write_text("sunset")
(root / "b.jpg").write_text("sea")
(root / "c.jpg").write_text("sunrise")
(root / "2025" / "c2.jpg").write_text("sunrise")
print(duplicates(root))
פלטOutput
[['2025/c2.jpg', 'c.jpg'], ['2025/copy of a.jpg', 'a.jpg']]

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

אתגרChallenge 2

מפרש cronA cron interpreter

תזכורת: מה ביקשוReminder: the task

כתבו matches(expr, when) שבודקת אם datetime מתאים לביטוי cron של חמישה שדות (דקה, שעה, יום בחודש, חודש, יום בשבוע כש-0 = ראשון). כל שדה יכול להיות *, מספר, רשימה (1,15), או */n (כל n). ואז next_match(expr, start) שמחזירה את הדקה הראשונה מ-start ואילך שמתאימה (חיפוש דקה אחרי דקה, עד שבוע קדימה).

Write matches(expr, when) checking whether a datetime fits a five-field cron expression (minute, hour, day of month, month, weekday with 0 = Sunday). Each field may be *, a number, a list (1,15), or */n (every n). Then next_match(expr, start) returning the first minute from start onward that matches (searching minute by minute, up to a week ahead).

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
main.py
from datetime import datetime, timedelta

def field_ok(text, value):
    if text == "*":
        return True
    if text.startswith("*/"):
        return value % int(text[2:]) == 0
    return value in {int(x) for x in text.split(",")}

def matches(expr, when):
    minute, hour, dom, month, dow = expr.split()
    values = [when.minute, when.hour, when.day, when.month, (when.weekday() + 1) % 7]
    return all(field_ok(t, v) for t, v in zip([minute, hour, dom, month, dow], values))

def next_match(expr, start):
    t = start.replace(second=0, microsecond=0)
    for _ in range(7 * 24 * 60):
        if matches(expr, t):
            return t
        t += timedelta(minutes=1)
    return None

start = datetime(2026, 3, 4, 22, 0)
print(next_match("30 21 * * *", start))
print(next_match("0 9 * * 0", start))
print(next_match("*/15 * * * *", datetime(2026, 3, 4, 10, 7)))
פלטOutput
2026-03-05 21:30:00
2026-03-08 09:00:00
2026-03-04 10:15:00

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

נבנה על ידיBuilt by Ariel Yohimovich