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

PythonPython
12
חלקPart 2: פונקציות וקוד אמיתיFunctions & real code כ-3 שעות (כולל הפסקה)About 3 hours (with a break)

קבציםFiles

קריאה וכתיבה, with, נתיבים עם pathlib וקידוד UTF-8.

Reading and writing, with, paths with pathlib and UTF-8 encoding.

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

עד עכשיו כל הנתונים נעלמו כשהתוכנית נגמרה. קובץ שומר אותם על הדיסק. open פותח קובץ, ו-with דואג לסגור אותו בסוף. תמיד מוסיפים encoding="utf-8" כדי שעברית תישמר נכון.

Until now all data vanished when the program ended. A file keeps it on disk. open opens a file, and with makes sure it closes at the end. Always add encoding="utf-8" so Hebrew is saved correctly.

write.py
with open("shelf.txt", "w", encoding="utf-8") as f:
    f.write("Dune\n")
    f.write("Matilda\n")
    f.write("הנסיך הקטן\n")
print("נשמר")
with open("shelf.txt", encoding="utf-8") as f:
    print(f.read())
with open("shelf.txt", "w", encoding="utf-8") as f:
    f.write("Dune\n")
    f.write("Matilda\n")
    f.write("The Little Prince\n")
print("saved")
with open("shelf.txt", encoding="utf-8") as f:
    print(f.read())
פלטOutput
נשמר
Dune
Matilda
הנסיך הקטן
saved
Dune
Matilda
The Little Prince
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

אנלוגיה מהחייםReal-life 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.

טעות נפוצהCommon mistake

כותבים מספר ישירות לקובץ. write מקבלת רק מחרוזות.

Writing a number straight to a file. write only accepts strings.

write.py
with open("pages.txt", "w", encoding="utf-8") as f:
    f.write(412)
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/write.py", line 2, in <module>
    f.write(412)
    ~~~~~~~^^^^^
TypeError: write() argument must be str, not int
בעברית פשוטה: In plain words: TypeError: write() argument must be str, not int: ממירים: f.write(f"{412}\n").TypeError: write() argument must be str, not int: convert: f.write(f"{412}\n").
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

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

הדרך הנוחה לקרוא קובץ היא לולאת for עליו: כל סיבוב נותן שורה אחת, כולל ה-\n שבסופה, ולכן מנקים עם strip. לקבצים קטנים read() מחזירה את כל התוכן.

The handy way to read a file is a for loop over it: each pass gives one line, including its trailing \n, so clean it with strip. For small files read() returns everything.

read.py
with open("shelf.txt", "w", encoding="utf-8") as f:
    f.write("Dune\nMatilda\nEmma\n")

books = []
with open("shelf.txt", encoding="utf-8") as f:
    for line in f:
        books.append(line.strip())
print(books)
print(len(books), "ספרים")
with open("shelf.txt", "w", encoding="utf-8") as f:
    f.write("Dune\nMatilda\nEmma\n")

books = []
with open("shelf.txt", encoding="utf-8") as f:
    for line in f:
        books.append(line.strip())
print(books)
print(len(books), "books")
פלטOutput
['Dune', 'Matilda', 'Emma']
3 ספרים
['Dune', 'Matilda', 'Emma']
3 books
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

אנלוגיה מהחייםReal-life 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.

טעות נפוצהCommon mistake

פותחים לקריאה קובץ שלא קיים.

Opening a missing file for reading.

read.py
with open("missing.txt", encoding="utf-8") as f:
    print(f.read())
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/read.py", line 1, in <module>
    with open("missing.txt", encoding="utf-8") as f:
         ~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
FileNotFoundError: [Errno 2] No such file or directory: 'missing.txt'
בעברית פשוטה: In plain words: FileNotFoundError: [Errno 2] No such file or directory: בודקים את השם ואת התיקייה הנוכחית, או משתמשים ב-Path("missing.txt").exists() לפני.FileNotFoundError: [Errno 2] No such file or directory: check the name and current folder, or use Path("missing.txt").exists() first.
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

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

המצב קובע מה עושים עם הקובץ. הכי מסוכן: "w" מוחק את כל מה שהיה בקובץ ברגע הפתיחה. כשרוצים להוסיף שורה ליומן, משתמשים ב-"a".

The mode decides what you do with the file. Most dangerous: "w" erases everything the moment it opens. To add a line to a log, use "a".

modes.py
with open("log.txt", "w", encoding="utf-8") as f:
    f.write("day 1: 40 pages\n")
with open("log.txt", "a", encoding="utf-8") as f:
    f.write("day 2: 55 pages\n")
with open("log.txt", "a", encoding="utf-8") as f:
    f.write("day 3: 20 pages\n")
with open("log.txt", encoding="utf-8") as f:
    print(f.read())
פלטOutput
day 1: 40 pages
day 2: 55 pages
day 3: 20 pages
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

אנלוגיה מהחייםReal-life 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.

טעות נפוצהCommon mistake

מנסים לכתוב לקובץ שנפתח לקריאה.

Writing to a file opened for reading.

modes.py
with open("log.txt", "w", encoding="utf-8") as f:
    f.write("x\n")
with open("log.txt", encoding="utf-8") as f:
    f.write("more\n")
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/modes.py", line 4, in <module>
    f.write("more\n")
    ~~~~~~~^^^^^^^^^^
io.UnsupportedOperation: not writable
בעברית פשוטה: In plain words: io.UnsupportedOperation: not writable: ברירת המחדל היא "r". כדי להוסיף פותחים עם "a".io.UnsupportedOperation: not writable: the default is "r". To add, open with "a".
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

מצב "a" מוסיף לסוף הקובץ.

Mode "a" adds to the end of the file.

עוד דוגמה: מוסיפים בלי למחוקOne more: add without erasing
example.py
with open("log.txt", "w", encoding="utf-8") as f:
    f.write("start\n")
with open("log.txt", "a", encoding="utf-8") as f:
    f.write("more\n")
print(open("log.txt", encoding="utf-8").read())
פלטOutput
start
more
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

04למה with?Why with?

with פותח משאב וסוגר אותו כשהבלוק נגמר, בכל מקרה. בלי with צריך לזכור f.close(), ואם שגיאה קורית לפני כן, הקובץ נשאר פתוח ולפעמים חלק מהכתיבה לא נשמר.

with opens a resource and closes it when the block ends, no matter what. Without with you must remember f.close(), and if an error happens first the file stays open and some writing may not be saved.

with_demo.py
with open("notes.txt", "w", encoding="utf-8") as f:
    f.write("first line\n")
    print("בתוך with, סגור?", f.closed)
print("אחרי with, סגור?", f.closed)
with open("notes.txt", "w", encoding="utf-8") as f:
    f.write("first line\n")
    print("inside with, closed?", f.closed)
print("after with, closed?", f.closed)
פלטOutput
בתוך with, סגור? False
אחרי with, סגור? True
inside with, closed? False
after with, closed? True
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

אנלוגיה מהחייםReal-life 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.

טעות נפוצהCommon mistake

קוראים מקובץ אחרי שה-with כבר סגר אותו.

Reading from a file after with has closed it.

with_demo.py
with open("notes.txt", "w", encoding="utf-8") as f:
    f.write("hi\n")
with open("notes.txt", encoding="utf-8") as f:
    pass
print(f.read())
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/with_demo.py", line 5, in <module>
    print(f.read())
          ~~~~~~^^
ValueError: I/O operation on closed file.
בעברית פשוטה: In plain words: ValueError: I/O operation on closed file.: כל העבודה עם הקובץ צריכה להיות בתוך הבלוק המוזח.ValueError: I/O operation on closed file.: all work with the file belongs inside the indented block.
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

כותבים שורות לקובץ וקוראים אותו חזרה.

Write lines to a file and read it back.

עוד דוגמה: יומן קטןOne more: a tiny diary
example.py
with open("diary.txt", "w", encoding="utf-8") as f:
    f.write("Sunny day\n")
    f.write("Ate pizza\n")
with open("diary.txt", encoding="utf-8") as f:
    for line in f:
        print("-", line.strip())
פלטOutput
- Sunny day
- Ate pizza
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

05נתיבים עם pathlibPaths with pathlib

pathlib מייצג נתיבים כאובייקטים. האופרטור / מחבר חלקי נתיב בלי לדאוג ל-\ של Windows או / של Mac. יש לו קיצורים כמו read_text ו-write_text לקבצים קטנים.

pathlib represents paths as objects. The / operator joins path parts without worrying about Windows \ or Mac /. It has shortcuts like read_text and write_text for small files.

paths.py
from pathlib import Path

data = Path("data")
data.mkdir(exist_ok=True)
file = data / "books.txt"
file.write_text("Dune\nEmma\n", encoding="utf-8")
print(file, file.exists(), file.suffix, file.stem)
print(file.read_text(encoding="utf-8").splitlines())
print(sorted(p.name for p in data.iterdir()))
פלטOutput
data/books.txt True .txt books
['Dune', 'Emma']
['books.txt']
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

אנלוגיה מהחייםReal-life 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

יוצרים תיקייה שכבר קיימת.

Creating a folder that already exists.

paths.py
from pathlib import Path
Path("data").mkdir()
Path("data").mkdir()
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/paths.py", line 3, in <module>
    Path("data").mkdir()
    ~~~~~~~~~~~~~~~~~~^^
  File "/usr/local/lib/python3.13/pathlib/_local.py", line 722, in mkdir
    os.mkdir(self, mode)
    ~~~~~~~~^^^^^^^^^^^^
FileExistsError: [Errno 17] File exists: 'data'
בעברית פשוטה: In plain words: FileExistsError: מוסיפים exist_ok=True, ואז זה בסדר גם אם התיקייה קיימת.FileExistsError: add exist_ok=True, then it's fine if the folder exists.
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

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

קידוד קובע איך תווים נשמרים כבתים. UTF-8 תומך בכל השפות. ב-Windows, open בלי encoding עלול לבחור קידוד ישן, ואז עברית נשמרת כג'יבריש או נופלת בשגיאה. לכן תמיד כותבים encoding="utf-8" במפורש.

An encoding decides how characters are stored as bytes. UTF-8 supports every language. On Windows, open without an encoding may pick an old one, so Hebrew gets saved as gibberish or crashes. So always write encoding="utf-8" explicitly.

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
שלום 📚
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

אנלוגיה מהחייםReal-life 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.

טעות נפוצהCommon mistake

קוראים קובץ UTF-8 עם קידוד אחר.

Reading a UTF-8 file with another encoding.

encoding.py
from pathlib import Path
Path("he.txt").write_text("שלום", encoding="utf-8")
print(Path("he.txt").read_text(encoding="ascii"))
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/encoding.py", line 3, in <module>
    print(Path("he.txt").read_text(encoding="ascii"))
          ~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^
  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 633, in read_text
    return f.read()
           ~~~~~~^^
  File "/usr/local/lib/python3.13/encodings/ascii.py", line 26, in decode
    return codecs.ascii_decode(input, self.errors)[0]
           ~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^
UnicodeDecodeError: 'ascii' codec can't decode byte 0xd7 in position 0: ordinal not in range(128)
בעברית פשוטה: In plain words: UnicodeDecodeError: הקובץ נשמר ב-UTF-8 וחייבים לקרוא אותו ב-UTF-8.UnicodeDecodeError: the file was saved as UTF-8 and must be read as UTF-8.
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

סיימתם את ההרצאה!Lecture complete!

עכשיו המצגת לחזרה מהירה, או ישר לתרגול.

Next: the slides for a quick review, or straight to practice.

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