חלק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.
הנקודות החשובותKey points
open(שם, "w", encoding="utf-8")open(name, "w", encoding="utf-8")f.write(טקסט)לא מוסיף ירידת שורהf.write(text)adds no newlinef.read()הכול כמחרוזת אחתf.read()all as one stringfor line in f:שורה אחרי שורהfor line in f:line by line"r"קריאה (ברירת מחדל)"r"read (default)"w"כתיבה מאפס"w"write from scratchwithסוגר את הקובץ לבדwithcloses the file for you- גם אם הייתה שגיאה באמצעEven if an error happened midway
Path("data") / "books.txt"Path("data") / "books.txt"
מונחיםTerms
- קובץ טקסטtext file: קובץ שמכיל תווים שאפשר לקרוא בעורך, כמו .txt, .csv, .py.A file of characters you can read in an editor, like .txt, .csv, .py.
- מצב פתיחהfile mode: האות השנייה ב-
open:"r"קריאה,"w"כתיבה (מוחק קודם!),"a"הוספה בסוף.The second argument ofopen:"r"read,"w"write (erases first!),"a"append. - with (מנהל הקשר)with (context manager):
with open(...) as f:פותח קובץ וסוגר אותו אוטומטית בסוף הבלוק, גם אם הייתה שגיאה.with open(...) as f:opens a file and closes it automatically at the end of the block, even after an error. - קידוד (encoding)encoding: הדרך שבה תווים נשמרים כבתים. ל-UTF-8 יש מקום לכל שפה, כולל עברית ואימוג'י.How characters are stored as bytes. UTF-8 covers every language, including Hebrew and emoji.
- pathlibpathlib: מודול שמייצג נתיבים כאובייקטים:
Path("data") / "books.txt". עובד אותו דבר ב-Windows וב-Mac.A module that represents paths as objects:Path("data") / "books.txt". Works the same on Windows and Mac.
Cheatsheet
כתיבהWriting
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())קריאהReading
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())מצביםModes
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:withwith
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)pathlibpathlib
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)קידודEncoding
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"))שגיאות שפגשנוErrors we met
| שגיאהError | מה זה אומרWhat it means | מה עושיםWhat to do |
|---|---|---|
TypeError | כותבים מספר ישירות לקובץ. write מקבלת רק מחרוזות.Writing a number straight to a file. write only accepts strings. | 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"). |
FileNotFoundError | פותחים לקריאה קובץ שלא קיים.Opening a missing file for reading. | 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. |
io.UnsupportedOperation | מנסים לכתוב לקובץ שנפתח לקריאה.Writing to a file opened for reading. | io.UnsupportedOperation: not writable: ברירת המחדל היא "r". כדי להוסיף פותחים עם "a".io.UnsupportedOperation: not writable: the default is "r". To add, open with "a". |
ValueError | קוראים מקובץ אחרי שה-with כבר סגר אותו.Reading from a file after with has closed it. | ValueError: I/O operation on closed file.: כל העבודה עם הקובץ צריכה להיות בתוך הבלוק המוזח.ValueError: I/O operation on closed file.: all work with the file belongs inside the indented block. |
FileExistsError | יוצרים תיקייה שכבר קיימת.Creating a folder that already exists. | FileExistsError: מוסיפים exist_ok=True, ואז זה בסדר גם אם התיקייה קיימת.FileExistsError: add exist_ok=True, then it's fine if the folder exists. |
UnicodeDecodeError | קוראים קובץ UTF-8 עם קידוד אחר.Reading a UTF-8 file with another encoding. | UnicodeDecodeError: הקובץ נשמר ב-UTF-8 וחייבים לקרוא אותו ב-UTF-8.UnicodeDecodeError: the file was saved as UTF-8 and must be read as UTF-8. |