נבנה על ידי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.

או Ctrl+Por Ctrl+P

הנקודות החשובותKey points

  • משהו שעושים שוב ושובSomething you do again and again
  • כללים ברורים, בלי שיקול דעתClear rules, no judgement
  • מילון סיומת → תיקייהA dict extension → folder
  • shutil.move(src, dst)shutil.move(src, dst)
  • p.stem, p.suffix, p.with_name(...)p.stem, p.suffix, p.with_name(...)
  • מספור עם אפסים: f"{i:03}"Numbering with zeros: f"{i:03}"
  • חותמת זמן בשם הקובץA timestamp in the file name
  • shutil.make_archive יוצר ZIPshutil.make_archive makes a ZIP
  • אוספים נתונים מתיקייהCollect data from a folder

מונחיםTerms

  • אוטומציהautomation: לתת למחשב לבצע משימה חוזרת במקומכם: לסדר קבצים, לגבות, לשלוח דוח.Letting the computer do a repetitive task for you: tidy files, back up, send a report.
  • shutilshutil: מודול סטנדרטי להעתקה, העברה ומחיקה של קבצים ותיקיות שלמות, וליצירת ארכיונים.A standard module for copying, moving and deleting files and whole folders, and making archives.
  • globglob: חיפוש קבצים לפי תבנית: Path(".").glob("*.txt"). rglob מחפש גם בתת-תיקיות.Finding files by pattern: Path(".").glob("*.txt"). rglob also searches subfolders.
  • חותמת זמןtimestamp: תאריך ושעה שמוסיפים לשם קובץ, כמו backup-2026-03-01.zip, כדי שגרסאות לא ידרסו זו את זו.A date and time added to a file name, like backup-2026-03-01.zip, so versions don't overwrite each other.
  • תזמוןscheduling: הרצה אוטומטית בזמן קבוע: cron ב-Mac/Linux, Task Scheduler ב-Windows.Automatic runs at a set time: cron on Mac/Linux, Task Scheduler on Windows.
  • הרצת ניסיון (dry run)dry run: מצב שבו הסקריפט רק מדפיס מה היה עושה, בלי לשנות כלום. בודקים כך לפני שמזיזים קבצים אמיתיים.A mode where the script only prints what it would do, changing nothing. Check this way before moving real files.

Cheatsheet

למהWhy
from pathlib import Path

inbox = Path("inbox")
inbox.mkdir(exist_ok=True)
for name in ["notes.txt", "cover.png", "shelf.csv", "photo.JPG", "todo.txt", "report.pdf"]:
    (inbox / name).write_text("x", encoding="utf-8")
from collections import Counter
סידורTidying
from pathlib import Path

inbox = Path("inbox")
inbox.mkdir(exist_ok=True)
for name in ["notes.txt", "cover.png", "shelf.csv", "photo.JPG", "todo.txt", "report.pdf"]:
    (inbox / name).write_text("x", encoding="utf-8")
import shutil
שמותNames
from pathlib import Path

trip = Path("trip")
trip.mkdir(exist_ok=True)
for n in ["IMG_8812.JPG", "IMG_8790.jpg", "IMG_8801.jpeg"]:
    (trip / n).write_text("x")
גיבויBackup
import shutil
import zipfile
from datetime import date, timedelta
from pathlib import Path

project = Path("shelf")
project.mkdir(exist_ok=True)
דוחReport
import json
from datetime import date
from pathlib import Path

log = [{"day": "2026-03-02", "title": "Dune", "pages": 60}, {"day": "2026-03-03", "title": "Dune", "pages": 45},
       {"day": "2026-03-05", "title": "Emma", "pages": 30}, {"day": "2026-03-06", "title": "Dune", "pages": 80}]
Path("reading_log.json").write_text(json.dumps(log))
תזמוןScheduling
# crontab -e  →  every day at 21:30
30 21 * * * /Users/you/python-course/.venv/bin/python /Users/you/python-course/backup.py >> /Users/you/python-course/backup.log 2>&1

שגיאות שפגשנוErrors we met

שגיאהErrorמה זה אומרWhat it meansמה עושיםWhat to do
AssertionErrorמחפשים *.jpg ומפספסים קבצים עם סיומת באותיות גדולות.Searching *.jpg and missing files with an uppercase extension.AssertionError: found 0: ...: התבנית רגישה לאותיות (ב-Linux וב-Mac לרוב). בודקים p.suffix.lower() == ".jpg".AssertionError: found 0: ...: the pattern is case-sensitive (on Linux, and often Mac). Check p.suffix.lower() == ".jpg".
AssertionErrorמזיזים לקובץ שכבר קיים ביעד.Moving onto a file that already exists at the destination.AssertionError: the old file was silently overwritten: ב-Mac וב-Linux, rename דורס בשקט. בודקים target.exists() לפני, ומוסיפים מספר לשם אם צריך.AssertionError: the old file was silently overwritten: on Mac and Linux, rename overwrites silently. Check target.exists() first, and add a number to the name if needed.
AssertionErrorממספרים בלי אפסים, והסדר משתבש.Numbering without zeros scrambles the order.AssertionError: sorted: ['photo-1.jpg', 'photo-10.jpg', 'photo-2.jpg']: מיון של טקסט משווה תו אחרי תו. f"{i:03}" פותר את זה.AssertionError: sorted: ['photo-1.jpg', 'photo-10.jpg', 'photo-2.jpg']: text sorting compares character by character. f"{i:03}" fixes it.
AssertionErrorשמים : של שעה בשם קובץ.Putting a time's : in a file name.AssertionError: 'backup-2026-03-01 09:30:00.zip': ...: ב-Windows אסור : בשם קובץ. משתמשים ב-strftime("%Y-%m-%d_%H-%M").AssertionError: 'backup-2026-03-01 09:30:00.zip': ...: Windows forbids : in file names. Use strftime("%Y-%m-%d_%H-%M").
UnicodeEncodeErrorכותבים דוח בעברית בלי encoding.Writing a Hebrew report without an encoding.UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128): (כאן הכרחנו ascii; ב-Windows ברירת המחדל יכולה להיות קידוד שאינו UTF-8.) תמיד encoding="utf-8".UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128): (here we forced ascii; on Windows the default may be a non-UTF-8 encoding.) Always encoding="utf-8".
FileNotFoundErrorסקריפט שעובד בטרמינל אבל נכשל מ-cron, כי הוא תלוי בתיקייה הנוכחית.A script that works in the terminal but fails from cron, because it depends on the current folder.FileNotFoundError: [Errno 2] No such file or directory: 'shelf.json': cron מריץ מתיקייה אחרת. בונים נתיבים יחסית לסקריפט: Path(__file__).parent / "shelf.json".FileNotFoundError: [Errno 2] No such file or directory: 'shelf.json': cron runs from a different folder. Build paths relative to the script: Path(__file__).parent / "shelf.json".

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