מפגש 28: קבצים ותיקיות בכמויות, תזמון, ודוחות אוטומטיים.Session 28: Files and folders in bulk, scheduling, and automatic reports.
קבצים ותיקיות בכמויות, תזמון, ודוחות אוטומטיים. בסוף המפגש מוסיפים צעד לפרויקט המלווה.Files and folders in bulk, scheduling, and automatic reports. At the end we add a step to the companion project.
מה נעשה היוםToday's plan
למהWhy
סידורTidying
שמותNames
גיבויBackup
דוחReport
תזמוןScheduling
עוברים על סדר היום ומזכירים את הפרויקט המלווה.Walk through the plan and mention the companion project.
נושאTopic 1
למהWhy
מה כדאי לאוטמט?What's worth automating?
משהו שעושים שוב ושובSomething you do again and again
כללים ברורים, בלי שיקול דעתClear rules, no judgement
טעות אנושית יקרהHuman mistakes are costly
אוטומציה היא אחד הדברים המתגמלים ביותר בפייתון: חמש דקות כל יום הן 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:
אנלוגיהAnalogy
אוטומציה היא כמו מדיח כלים: צריך ללמוד פעם אחת איך להעמיס אותו, ואז הוא חוסך לכם עבודה כל ערב.Automation is like a dishwasher: learn once how to load it, and it saves you work every evening.
שואלים אם מישהו מכיר דוגמה נוספת מהחיים.Ask for another real-life example.
סקריפט שמזיז קבצים יכול לעשות נזק מהר. לכן כותבים קודם הרצת ניסיון: פרמטר 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.
אנלוגיהAnalogy
הרצת ניסיון היא כמו לסמן בעיפרון לפני שקודחים בקיר: אם הסימון במקום הלא נכון, מוחקים בלי חור.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.
שואלים אם מישהו מכיר דוגמה נוספת מהחיים.Ask for another real-life example.
מספור עם אפסים: f"{i:03}"Numbering with zeros: f"{i:03}"
ממיינים לפני שממספריםSort before numbering
שינוי שמות של מאות תמונות הוא משימה קלאסית. 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.
אנלוגיהAnalogy
אפסים מובילים הם כמו מספרי מושבים באולם: 007 תמיד לפני 010, גם כשמסדרים לפי האלף-בית.Leading zeros are like seat numbers in a hall: 007 always comes before 010, even when sorted alphabetically.
שואלים אם מישהו מכיר דוגמה נוספת מהחיים.Ask for another real-life example.
shutil.make_archive יוצר ZIPshutil.make_archive makes a ZIP
שומרים רק את N האחרוניםKeep only the last N
גיבוי טוב הוא אוטומטי, עם חותמת זמן בשם, ולא אוכל את כל הדיסק. 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().)
אנלוגיהAnalogy
גיבוי עם תאריך הוא כמו תמונות בגלריה עם תאריך: יודעים בדיוק איך הדברים נראו ביום מסוים, ולא מתבלבלים בין "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".
שואלים אם מישהו מכיר דוגמה נוספת מהחיים.Ask for another real-life example.
נושאTopic 5
דוחReport
דוח אוטומטיAn automatic report
אוספים נתונים מתיקייהCollect data from a folder
כותבים Markdown/טקסטWrite Markdown/text
שמים בתיקיית reports/ עם תאריךPut it in reports/ with a date
דוח שבועי הוא אוטומציה מושלמת: אוסף מספרים, מסדר, וכותב קובץ שאפשר לפתוח או לשלוח. כאן הדוח נכתב ב-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.
אנלוגיהAnalogy
דוח אוטומטי הוא כמו דף סיכום שמישהו מניח לכם על השולחן כל יום ראשון: אתם רק קוראים.An automatic report is like a summary sheet someone leaves on your desk every Sunday: you just read it.
שואלים אם מישהו מכיר דוגמה נוספת מהחיים.Ask for another real-life example.
כדי שסקריפט ירוץ כל יום, נותנים למערכת ההפעלה לתזמן אותו. ב-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:
אנלוגיהAnalogy
cron הוא כמו שעון מעורר למחשב: מכוונים פעם אחת, והוא מצלצל לבד בכל יום, גם אם שכחתם.cron is like an alarm clock for the computer: set it once, and it rings every day by itself, even if you forget.
שואלים אם מישהו מכיר דוגמה נוספת מהחיים.Ask for another real-life example.
טעות נפוצהCommon mistake
backup.py
import os
from pathlib import Path
os.chdir("/")
print(Path("shelf.json").read_text())
מה Python עונהWhat Python says
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".
סקריפט שעובד בטרמינל אבל נכשל מ-cron, כי הוא תלוי בתיקייה הנוכחית.A script that works in the terminal but fails from cron, because it depends on the current folder.
משהו שעושים שוב ושובSomething you do again and again
מה כדאי לאוטמט?What's worth automating?
כללים ברורים, בלי שיקול דעתClear rules, no judgement