קבצים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.
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())נשמר Dune Matilda הנסיך הקטן
saved Dune Matilda The Little Prince
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
קובץ הוא כמו מחברת: הזיכרון של התוכנית הוא לוח מחיק שנמחק בסוף השיעור, והמחברת נשארת בתיק למחר.
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.
כותבים מספר ישירות לקובץ. write מקבלת רק מחרוזות.
Writing a number straight to a file. write only accepts strings.
with open("pages.txt", "w", encoding="utf-8") as f:
f.write(412)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 intTypeError: 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
מה קורה עכשיו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.
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")['Dune', 'Matilda', 'Emma'] 3 ספרים
['Dune', 'Matilda', 'Emma'] 3 books
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
לקרוא קובץ שורה אחרי שורה זה כמו לקרוא רשימת קניות מלמעלה למטה: לא צריך לזכור את כולה בבת אחת.
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.
פותחים לקריאה קובץ שלא קיים.
Opening a missing file for reading.
with open("missing.txt", encoding="utf-8") as f:
print(f.read())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'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
מה קורה עכשיו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".
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())day 1: 40 pages day 2: 55 pages day 3: 20 pages
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
"w" הוא לקרוע את הדף ולהתחיל דף חדש. "a" הוא להמשיך לכתוב בשורה הבאה של אותו דף.
"w" is tearing out the page and starting fresh. "a" is carrying on writing on the next line of the same page.
מנסים לכתוב לקובץ שנפתח לקריאה.
Writing to a file opened for reading.
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")Traceback (most recent call last):
File "/Users/you/python-course/modes.py", line 4, in <module>
f.write("more\n")
~~~~~~~^^^^^^^^^^
io.UnsupportedOperation: not writableio.UnsupportedOperation: not writable: ברירת המחדל היא "r". כדי להוסיף פותחים עם "a".io.UnsupportedOperation: not writable: the default is "r". To add, open with "a".צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
מצב "a" מוסיף לסוף הקובץ.
Mode "a" adds to the end of the file.
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())start more
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיו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 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)בתוך with, סגור? False אחרי with, סגור? True
inside with, closed? False after with, closed? True
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
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.
קוראים מקובץ אחרי שה-with כבר סגר אותו.
Reading from a file after with has closed it.
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())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.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
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
כותבים שורות לקובץ וקוראים אותו חזרה.
Write lines to a file and read it back.
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())- Sunny day - Ate pizza
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיו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.
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()))data/books.txt True .txt books ['Dune', 'Emma'] ['books.txt']
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
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.
יוצרים תיקייה שכבר קיימת.
Creating a folder that already exists.
from pathlib import Path
Path("data").mkdir()
Path("data").mkdir()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'FileExistsError: מוסיפים exist_ok=True, ואז זה בסדר גם אם התיקייה קיימת.FileExistsError: add exist_ok=True, then it's fine if the folder exists.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיו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.
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"))6 תווים 13 בתים שלום 📚
6 characters 13 bytes שלום 📚
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
קידוד הוא כמו שפת הסימנים שבה רושמים מכתב: אם כתבתם בעברית ומישהו קורא בצופן של רוסית, הוא יקבל שטויות.
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.
קוראים קובץ UTF-8 עם קידוד אחר.
Reading a UTF-8 file with another encoding.
from pathlib import Path
Path("he.txt").write_text("שלום", encoding="utf-8")
print(Path("he.txt").read_text(encoding="ascii"))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)UnicodeDecodeError: הקובץ נשמר ב-UTF-8 וחייבים לקרוא אותו ב-UTF-8.UnicodeDecodeError: the file was saved as UTF-8 and must be read as UTF-8.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
סיימתם את ההרצאה!Lecture complete!
עכשיו המצגת לחזרה מהירה, או ישר לתרגול.
Next: the slides for a quick review, or straight to practice.