אוטומציה של משימותAutomating tasks
קבצים ותיקיות בכמויות, תזמון, ודוחות אוטומטיים.
Files and folders in bulk, scheduling, and automatic reports.
01מה כדאי לאוטמט?What's worth automating?
אוטומציה היא אחד הדברים המתגמלים ביותר בפייתון: חמש דקות כל יום הן 30 שעות בשנה. מועמדים טובים: סידור הורדות, גיבויים, שינוי שמות למאות קבצים, דוח שבועי. נתחיל מלספור מה יש בתיקייה בעזרת glob:
Automation is one of Python's most rewarding uses: five minutes a day is 30 hours a year. Good candidates: tidying downloads, backups, renaming hundreds of files, a weekly report. Let's start by counting what's in a folder with glob:
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
kinds = Counter(p.suffix.lower() for p in inbox.glob("*"))
print(kinds)
print(sorted(p.name for p in inbox.glob("*.txt")))Counter({'.txt': 2, '.png': 1, '.pdf': 1, '.csv': 1, '.jpg': 1})
['notes.txt', 'todo.txt']אוטומציה היא כמו מדיח כלים: צריך ללמוד פעם אחת איך להעמיס אותו, ואז הוא חוסך לכם עבודה כל ערב.
Automation is like a dishwasher: learn once how to load it, and it saves you work every evening.
מחפשים *.jpg ומפספסים קבצים עם סיומת באותיות גדולות.
Searching *.jpg and missing files with an uppercase extension.
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")
jpgs = list(inbox.glob("*.jpg"))
assert len(jpgs) == 1, f"found {len(jpgs)}: photo.JPG has a capital extension"Traceback (most recent call last):
File "/Users/you/python-course/count.py", line 8, in <module>
assert len(jpgs) == 1, f"found {len(jpgs)}: photo.JPG has a capital extension"
^^^^^^^^^^^^^^
AssertionError: found 0: photo.JPG has a capital extensionAssertionError: 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".02לסדר תיקייהTidying a folder
סקריפט שמזיז קבצים יכול לעשות נזק מהר. לכן כותבים קודם הרצת ניסיון: פרמטר dry=True שבו הסקריפט רק מדפיס מה היה עושה. כשהרשימה נראית נכון, מריצים באמת. shutil.move מעביר קובץ, ו-mkdir(exist_ok=True) יוצר תיקייה אם חסרה.
A script that moves files can do damage fast. So first write a dry run: a dry=True parameter where the script only prints what it would do. When the list looks right, run it for real. shutil.move moves a file, and mkdir(exist_ok=True) creates a folder if missing.
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
FOLDERS = {".txt": "text", ".csv": "data", ".png": "images", ".jpg": "images", ".pdf": "docs"}
def tidy(folder, dry=True):
moved = 0
for f in sorted(folder.iterdir()):
if not f.is_file():
continue
target = folder / FOLDERS.get(f.suffix.lower(), "other")
print(("[dry] " if dry else "") + f"{f.name} -> {target.name}/")
if not dry:
target.mkdir(exist_ok=True)
shutil.move(str(f), str(target / f.name))
moved += 1
return moved
tidy(inbox)
print("moved:", tidy(inbox, dry=False))
print(sorted(str(p.relative_to(inbox)) for p in inbox.rglob("*") if p.is_file()))[dry] cover.png -> images/ [dry] notes.txt -> text/ [dry] photo.JPG -> images/ [dry] report.pdf -> docs/ [dry] shelf.csv -> data/ [dry] todo.txt -> text/ cover.png -> images/ notes.txt -> text/ photo.JPG -> images/ report.pdf -> docs/ shelf.csv -> data/ todo.txt -> text/ moved: 6 ['data/shelf.csv', 'docs/report.pdf', 'images/cover.png', 'images/photo.JPG', 'text/notes.txt', 'text/todo.txt']
הרצת ניסיון היא כמו לסמן בעיפרון לפני שקודחים בקיר: אם הסימון במקום הלא נכון, מוחקים בלי חור.
A dry run is like marking with a pencil before drilling the wall: if the mark's in the wrong place, you erase it, no hole.
מזיזים לקובץ שכבר קיים ביעד.
Moving onto a file that already exists at the destination.
from pathlib import Path
Path("a").mkdir(exist_ok=True)
Path("b").mkdir(exist_ok=True)
Path("a/notes.txt").write_text("new")
Path("b/notes.txt").write_text("old, important")
Path("a/notes.txt").rename("b/notes.txt")
assert Path("b/notes.txt").read_text() == "old, important", "the old file was silently overwritten"Traceback (most recent call last):
File "/Users/you/python-course/tidy.py", line 7, in <module>
assert Path("b/notes.txt").read_text() == "old, important", "the old file was silently overwritten"
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: the old file was silently overwrittenAssertionError: 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.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
מחליטים לאיזו תיקייה כל קובץ הולך לפי הסיומת.
Decide which folder each file goes to by its ending.
files = ["a.jpg", "b.pdf", "c.png", "notes.txt"]
KINDS = {".jpg": "images", ".png": "images", ".pdf": "docs"}
for f in files:
ext = f[f.rfind("."):]
print(f, "->", KINDS.get(ext, "other"))a.jpg -> images b.pdf -> docs c.png -> images notes.txt -> other
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
03שינוי שמות בכמותRenaming in bulk
שינוי שמות של מאות תמונות הוא משימה קלאסית. p.stem הוא השם בלי הסיומת, ו-with_name נותן נתיב חדש באותה תיקייה. מספור עם אפסים מובילים (001, 002) שומר על סדר נכון גם במיון אלפביתי.
Renaming hundreds of photos is a classic task. p.stem is the name without the extension, and with_name gives a new path in the same folder. Numbering with leading zeros (001, 002) keeps the right order even in alphabetical sorting.
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")
for i, p in enumerate(sorted(trip.iterdir()), 1):
new = p.with_name(f"eilat-{i:03}{p.suffix.lower().replace('.jpeg', '.jpg')}")
print(p.name, "->", new.name)
p.rename(new)
print(sorted(x.name for x in trip.iterdir()))IMG_8790.jpg -> eilat-001.jpg IMG_8801.jpeg -> eilat-002.jpg IMG_8812.JPG -> eilat-003.jpg ['eilat-001.jpg', 'eilat-002.jpg', 'eilat-003.jpg']
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
אפסים מובילים הם כמו מספרי מושבים באולם: 007 תמיד לפני 010, גם כשמסדרים לפי האלף-בית.
Leading zeros are like seat numbers in a hall: 007 always comes before 010, even when sorted alphabetically.
ממספרים בלי אפסים, והסדר משתבש.
Numbering without zeros scrambles the order.
names = [f"photo-{i}.jpg" for i in (1, 2, 10)]
assert sorted(names) == names, f"sorted: {sorted(names)}"Traceback (most recent call last):
File "/Users/you/python-course/rename.py", line 2, in <module>
assert sorted(names) == names, f"sorted: {sorted(names)}"
^^^^^^^^^^^^^^^^^^^^^^
AssertionError: sorted: ['photo-1.jpg', 'photo-10.jpg', 'photo-2.jpg']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.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
04גיבוי מתוארךA dated backup
גיבוי טוב הוא אוטומטי, עם חותמת זמן בשם, ולא אוכל את כל הדיסק. shutil.make_archive דוחס תיקייה שלמה ל-ZIP בשורה אחת. אחר כך מוחקים גיבויים ישנים ומשאירים רק את האחרונים. (כאן התאריך קבוע כדי שהפלט יהיה זהה בכל הרצה; אצלכם: date.today().)
A good backup is automatic, has a timestamp in its name, and doesn't eat the whole disk. shutil.make_archive zips a whole folder in one line. Then delete old backups and keep only the latest. (Here the date is fixed so the output is the same on every run; on your machine: date.today().)
import shutil
import zipfile
from datetime import date, timedelta
from pathlib import Path
project = Path("shelf")
project.mkdir(exist_ok=True)
(project / "shelf.py").write_text("print('shelf')\n")
(project / "shelf.json").write_text("[]\n")
backups = Path("backups")
backups.mkdir(exist_ok=True)
def backup(day, keep=3):
name = backups / f"shelf-{day.isoformat()}"
zip_path = shutil.make_archive(str(name), "zip", root_dir=project)
old = sorted(backups.glob("shelf-*.zip"))[:-keep]
for f in old:
f.unlink()
return Path(zip_path).name
start = date(2026, 3, 1)
for i in range(5):
backup(start + timedelta(days=i))
print(sorted(p.name for p in backups.iterdir()))
print(zipfile.ZipFile(backups / "shelf-2026-03-05.zip").namelist())['shelf-2026-03-03.zip', 'shelf-2026-03-04.zip', 'shelf-2026-03-05.zip'] ['shelf.py', 'shelf.json']
גיבוי עם תאריך הוא כמו תמונות בגלריה עם תאריך: יודעים בדיוק איך הדברים נראו ביום מסוים, ולא מתבלבלים בין "final" ל-"final2".
A dated backup is like dated photos in a gallery: you know exactly how things looked on a given day, no mixing up "final" and "final2".
שמים : של שעה בשם קובץ.
Putting a time's : in a file name.
from datetime import datetime
name = f"backup-{datetime(2026, 3, 1, 9, 30)}.zip"
assert ":" not in name, f"{name!r}: Windows does not allow : in file names"Traceback (most recent call last):
File "/Users/you/python-course/backup.py", line 3, in <module>
assert ":" not in name, f"{name!r}: Windows does not allow : in file names"
^^^^^^^^^^^^^^^
AssertionError: 'backup-2026-03-01 09:30:00.zip': Windows does not allow : in file namesAssertionError: '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").צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
05דוח אוטומטיAn automatic report
דוח שבועי הוא אוטומציה מושלמת: אוסף מספרים, מסדר, וכותב קובץ שאפשר לפתוח או לשלוח. כאן הדוח נכתב ב-Markdown, פורמט טקסט פשוט שנראה יפה ב-GitHub ובאפליקציות הערות.
A weekly report is perfect automation: gather numbers, arrange them, and write a file you can open or send. Here the report is written in Markdown, a simple text format that looks good on GitHub and in note apps.
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))
def weekly_report(today):
entries = json.loads(Path("reading_log.json").read_text())
per_book = {}
for e in entries:
per_book[e["title"]] = per_book.get(e["title"], 0) + e["pages"]
lines = [f"# Reading report, week ending {today.isoformat()}", "",
f"- Days read: {len({e['day'] for e in entries})}", f"- Pages: {sum(per_book.values())}", "", "| Book | Pages |", "|---|---|"]
lines += [f"| {t} | {p} |" for t, p in sorted(per_book.items(), key=lambda kv: -kv[1])]
out = Path("reports") / f"week-{today.isoformat()}.md"
out.parent.mkdir(exist_ok=True)
out.write_text("\n".join(lines) + "\n", encoding="utf-8")
return out
path = weekly_report(date(2026, 3, 7))
print(path)
print(path.read_text())reports/week-2026-03-07.md # Reading report, week ending 2026-03-07 - Days read: 4 - Pages: 215 | Book | Pages | |---|---| | Dune | 185 | | Emma | 30 |
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
דוח אוטומטי הוא כמו דף סיכום שמישהו מניח לכם על השולחן כל יום ראשון: אתם רק קוראים.
An automatic report is like a summary sheet someone leaves on your desk every Sunday: you just read it.
כותבים דוח בעברית בלי encoding.
Writing a Hebrew report without an encoding.
from pathlib import Path
Path("r.md").write_text("דוח", encoding="ascii")Traceback (most recent call last):
File "/Users/you/python-course/report.py", line 2, in <module>
Path("r.md").write_text("דוח", encoding="ascii")
~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.13/pathlib/_local.py", line 555, in write_text
return PathBase.write_text(self, data, encoding, errors, newline)
~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.13/pathlib/_abc.py", line 652, in write_text
return f.write(data)
~~~~~~~^^^^^^
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128)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".צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
06להריץ לבד בזמן קבועRunning on its own, on time
כדי שסקריפט ירוץ כל יום, נותנים למערכת ההפעלה לתזמן אותו. ב-Mac וב-Linux, cron: שורה בקובץ crontab עם חמישה שדות זמן (דקה, שעה, יום בחודש, חודש, יום בשבוע). ב-Windows, Task Scheduler עם אשף גרפי. שני כללים: נתיבים מלאים בלבד (cron לא יודע מאיפה הרצתם), והפלט נשמר לקובץ לוג, כי אין מסך. בפייתון אפשר גם לחשב מתי תהיה ההרצה הבאה:
To run a script every day, let the operating system scheduling it. On Mac and Linux, cron: a line in a crontab file with five time fields (minute, hour, day of month, month, weekday). On Windows, Task Scheduler with a graphical wizard. Two rules: full paths only (cron doesn't know where you ran from), and save output to a log file, since there's no screen. In Python you can also work out when the next run is:
# 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>&1from datetime import datetime, timedelta
def next_run(now, hour, minute):
run = now.replace(hour=hour, minute=minute, second=0, microsecond=0)
if run <= now:
run += timedelta(days=1)
return run
for now in [datetime(2026, 3, 1, 20, 0), datetime(2026, 3, 1, 22, 15)]:
print(now.strftime("%H:%M"), "->", next_run(now, 21, 30).strftime("%a %d %b %H:%M"))20:00 -> Sun 01 Mar 21:30 22:15 -> Mon 02 Mar 21:30
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
cron הוא כמו שעון מעורר למחשב: מכוונים פעם אחת, והוא מצלצל לבד בכל יום, גם אם שכחתם.
cron is like an alarm clock for the computer: set it once, and it rings every day by itself, even if you forget.
סקריפט שעובד בטרמינל אבל נכשל מ-cron, כי הוא תלוי בתיקייה הנוכחית.
A script that works in the terminal but fails from cron, because it depends on the current folder.
import os
from pathlib import Path
os.chdir("/")
print(Path("shelf.json").read_text())Traceback (most recent call last):
File "/Users/you/python-course/backup.py", line 4, in <module>
print(Path("shelf.json").read_text())
~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^
File "/usr/local/lib/python3.13/pathlib/_local.py", line 546, in read_text
return PathBase.read_text(self, encoding, errors, newline)
~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.13/pathlib/_abc.py", line 632, in read_text
with self.open(mode='r', encoding=encoding, errors=errors, newline=newline) as f:
~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.13/pathlib/_local.py", line 537, in open
return io.open(self, mode, buffering, encoding, errors, newline)
~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
FileNotFoundError: [Errno 2] No such file or directory: 'shelf.json'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".סיימתם את ההרצאה!Lecture complete!
עכשיו המצגת לחזרה מהירה, או ישר לתרגול.
Next: the slides for a quick review, or straight to practice.