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

חזרה למפגשBack
PythonPython

קבציםFiles

מפגש 12: קריאה וכתיבה, with, נתיבים עם pathlib וקידוד UTF-8.Session 12: Reading and writing, with, paths with pathlib and UTF-8 encoding.

מה נעשה היוםToday's plan

  • כתיבהWriting
  • קריאהReading
  • מצביםModes
  • withwith
  • pathlibpathlib
  • קידודEncoding
נושאTopic 1

כתיבהWriting

לכתוב לקובץWriting a file

  • open(שם, "w", encoding="utf-8")open(name, "w", encoding="utf-8")
  • f.write(טקסט) לא מוסיף ירידת שורהf.write(text) adds no newline
  • "w" מוחק את התוכן הקודם"w" erases the old content

אנלוגיהAnalogy

קובץ הוא כמו מחברת: הזיכרון של התוכנית הוא לוח מחיק שנמחק בסוף השיעור, והמחברת נשארת בתיק למחר.A file is like a notebook: the program's memory is a whiteboard wiped at the end of the lesson, while the notebook stays in your bag for tomorrow.
נושאTopic 2

קריאהReading

לקרוא מקובץReading a file

  • f.read() הכול כמחרוזת אחתf.read() all as one string
  • for line in f: שורה אחרי שורהfor line in f: line by line
  • .strip() מסיר את ה-\n.strip() removes the \n

אנלוגיהAnalogy

לקרוא קובץ שורה אחרי שורה זה כמו לקרוא רשימת קניות מלמעלה למטה: לא צריך לזכור את כולה בבת אחת.Reading a file line by line is like reading a shopping list top to bottom: no need to hold it all in your head at once.
נושאTopic 3

מצביםModes

מצבי פתיחה: r, w, aModes: r, w, a

  • "r" קריאה (ברירת מחדל)"r" read (default)
  • "w" כתיבה מאפס"w" write from scratch
  • "a" הוספה לסוף"a" append to the end

אנלוגיהAnalogy

"w" הוא לקרוע את הדף ולהתחיל דף חדש. "a" הוא להמשיך לכתוב בשורה הבאה של אותו דף."w" is tearing out the page and starting fresh. "a" is carrying on writing on the next line of the same page.
נושאTopic 4

withwith

למה with?Why with?

  • with סוגר את הקובץ לבדwith closes the file for you
  • גם אם הייתה שגיאה באמצעEven if an error happened midway
  • קובץ שלא נסגר עלול לא להישמרAn unclosed file may not be saved

אנלוגיהAnalogy

with הוא כמו דלת עם מחזיר אוטומטי: נכנסים, עושים מה שצריך, והדלת נסגרת לבד אחריכם, גם אם יצאתם בריצה.with is like a self-closing door: you go in, do what you need, and it shuts behind you, even if you ran out.
נושאTopic 5

pathlibpathlib

נתיבים עם pathlibPaths with pathlib

  • Path("data") / "books.txt"Path("data") / "books.txt"
  • .exists(), .mkdir(), .read_text().exists(), .mkdir(), .read_text()
  • עובד אותו דבר ב-Windows וב-MacWorks the same on Windows and Mac

אנלוגיהAnalogy

pathlib הוא כמו GPS לקבצים: אומרים לו "תיקייה data, ובה books.txt", והוא יודע לבנות את הכתובת בכל מדינה.pathlib is like a GPS for files: tell it "folder data, and in it books.txt" and it builds the address in any country.

טעות נפוצהCommon mistake

paths.py
from pathlib import Path
Path("data").mkdir()
Path("data").mkdir()
מה Python עונהWhat Python says
FileExistsError: [Errno 17] File exists: 'data'
FileExistsError: מוסיפים exist_ok=True, ואז זה בסדר גם אם התיקייה קיימת.FileExistsError: add exist_ok=True, then it's fine if the folder exists.
נושאTopic 6

קידודEncoding

עברית בקבצים: UTF-8Hebrew in files: UTF-8

  • תמיד encoding="utf-8"Always encoding="utf-8"
  • קידוד אחר = ג'יבריש או שגיאהAnother encoding = gibberish or an error
  • Windows לפעמים בוחר קידוד אחרWindows sometimes picks another one
שאלה לכיתהQuestion for the class

מה ידפיס הקוד?What will this print?

python
text = "שלום 📚"
data = text.encode("utf-8")
print(len(text), "תווים")
print(len(data), "בתים")
print(data.decode("utf-8"))
text = "שלום 📚"
data = text.encode("utf-8")
print(len(text), "characters")
print(len(data), "bytes")
print(data.decode("utf-8"))

    קידודEncoding

    encoding.py
    text = "שלום 📚"
    data = text.encode("utf-8")
    print(len(text), "תווים")
    print(len(data), "בתים")
    print(data.decode("utf-8"))
    text = "שלום 📚"
    data = text.encode("utf-8")
    print(len(text), "characters")
    print(len(data), "bytes")
    print(data.decode("utf-8"))
    פלטOutput
    6 תווים
    13 בתים
    שלום 📚
    6 characters
    13 bytes
    שלום 📚

    אנלוגיהAnalogy

    קידוד הוא כמו שפת הסימנים שבה רושמים מכתב: אם כתבתם בעברית ומישהו קורא בצופן של רוסית, הוא יקבל שטויות.An encoding is like the alphabet a letter is written in: if you wrote in Hebrew and someone reads it with a Russian cipher, they get nonsense.

    open(שם, "w", encoding="utf-8")open(name, "w", encoding="utf-8")

    f.write(טקסט) לא מוסיף ירידת שורהf.write(text) adds no newline

    "w" מוחק את התוכן הקודם"w" erases the old content

    f.read() הכול כמחרוזת אחתf.read() all as one string

    for line in f: שורה אחרי שורהfor line in f: line by line

    .strip() מסיר את ה-\n.strip() removes the \n

    "r" קריאה (ברירת מחדל)"r" read (default)

    "w" כתיבה מאפס"w" write from scratch

    "a" הוספה לסוף"a" append to the end

    with סוגר את הקובץ לבדwith closes the file for you

    גם אם הייתה שגיאה באמצעEven if an error happened midway

    קובץ שלא נסגר עלול לא להישמרAn unclosed file may not be saved

    Path("data") / "books.txt"Path("data") / "books.txt"

    .exists(), .mkdir(), .read_text().exists(), .mkdir(), .read_text()

    עובד אותו דבר ב-Windows וב-MacWorks the same on Windows and Mac

    מה למדנוWhat we learned

    • open(שם, "w", encoding="utf-8")open(name, "w", encoding="utf-8")
    • f.read() הכול כמחרוזת אחתf.read() all as one string
    • "r" קריאה (ברירת מחדל)"r" read (default)
    • with סוגר את הקובץ לבדwith closes the file for you
    • Path("data") / "books.txt"Path("data") / "books.txt"
    • תמיד encoding="utf-8"Always encoding="utf-8"

    עכשיו לתרגולNow, practice

    5 תרגילים ו-2 אתגרים, עם בדיקה אוטומטית5 exercises and 2 challenges, auto-checked
    הערות מרצהSpeaker notes

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