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

PythonPython
21
חלקPart 4: נתונים ורשתData & the web כ-3 שעות (כולל הפסקה)About 3 hours (with a break)

JSON ו-CSVJSON & CSV

שמירה בפורמטים מקובלים, ייבוא וייצוא.

Saving in standard formats, import and export.

01מה זה JSON?What is JSON?

JSON הוא הדרך הנפוצה בעולם לשמור ולשלוח נתונים מובנים. הוא נראה כמעט כמו מילונים ורשימות של פייתון, עם שלושה הבדלים קטנים: true, false ו-null באותיות קטנות, ומחרוזות תמיד במירכאות כפולות. json.dumps הופך אובייקט פייתון למחרוזת JSON, ו-json.loads עושה את ההפך.

JSON is the world's most common way to store and send structured data. It looks almost like Python dicts and lists, with three small differences: true, false and null in lowercase, and strings always in double quotes. json.dumps turns a Python object into a JSON string, and json.loads does the reverse.

json_demo.py
import json

book = {"title": "Dune", "pages": 412, "read": True, "rating": None, "tags": ["sci-fi"]}
text = json.dumps(book)
print(text)
print(type(text))
back = json.loads(text)
print(back["tags"][0], back == book)
פלטOutput
{"title": "Dune", "pages": 412, "read": true, "rating": null, "tags": ["sci-fi"]}
<class 'str'>
sci-fi 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

JSON הוא כמו שפה בינלאומית לנתונים: פייתון, JavaScript ואפליקציה בטלפון מדברים שפות שונות, אבל כולם מבינים JSON.

JSON is like an international language for data: Python, JavaScript and a phone app speak different languages, but all understand JSON.

טעות נפוצהCommon mistake

כותבים JSON עם מירכאות בודדות, כמו בפייתון.

Writing JSON with single quotes, like in Python.

json_demo.py
import json
print(json.loads("{'title': 'Dune'}"))
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/json_demo.py", line 2, in <module>
    print(json.loads("{'title': 'Dune'}"))
          ~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.13/json/__init__.py", line 352, in loads
    return _default_decoder.decode(s)
           ~~~~~~~~~~~~~~~~~~~~~~~^^^
  File "/usr/local/lib/python3.13/json/decoder.py", line 345, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
               ~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.13/json/decoder.py", line 361, in raw_decode
    obj, end = self.scan_once(s, idx)
               ~~~~~~~~~~~~~~^^^^^^^^
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
בעברית פשוטה: In plain words: json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1): ב-JSON רק מירכאות כפולות. אל תכתבו JSON ביד: תנו ל-json.dumps לייצר אותו.json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1): JSON allows only double quotes. Don't hand-write JSON: let json.dumps produce it.
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

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

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

מסך הפלטOutput screen

json.dumps הופך מילון לטקסט, ו-loads מחזיר אותו.

json.dumps turns a dict into text, and loads brings it back.

עוד דוגמה: שמירת הגדרותOne more: saving settings
example.py
import json
settings = {"volume": 7, "dark": True}
text = json.dumps(settings)
print(text)
back = json.loads(text)
print(back["volume"] + 1)
פלטOutput
{"volume": 7, "dark": true}
8
צפו בהרצה צעד אחר צעד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

02לשמור ולטעון קובץ JSONSaving and loading a JSON file

בלי s בסוף, הפונקציות עובדות ישירות עם קובץ: json.dump כותבת ו-json.load קוראת. indent=2 מסדר את הקובץ בשורות ורווחים, ו-ensure_ascii=False שומר עברית כמו שהיא ולא כ-\u05d3. כך המדף נשמר כולו, עם כל המבנה, בשורה אחת של קוד.

Without the s at the end, the functions work directly with a file: json.dump writes and json.load reads. indent=2 lays the file out in lines and spaces, and ensure_ascii=False keeps Hebrew as it is instead of \u05d3. That saves the whole shelf, structure and all, in one line of code.

save_json.py
import json

shelf = [{"title": "Dune", "author": "Frank Herbert", "pages": 412},
         {"title": "הנסיך הקטן", "author": "Antoine de Saint-Exupéry", "pages": 96}]

with open("shelf.json", "w", encoding="utf-8") as f:
    json.dump(shelf, f, indent=2, ensure_ascii=False)

print(open("shelf.json", encoding="utf-8").read())

with open("shelf.json", encoding="utf-8") as f:
    loaded = json.load(f)
print(len(loaded), loaded[1]["title"])
import json

shelf = [{"title": "Dune", "author": "Frank Herbert", "pages": 412},
         {"title": "The Little Prince", "author": "Antoine de Saint-Exupéry", "pages": 96}]

with open("shelf.json", "w", encoding="utf-8") as f:
    json.dump(shelf, f, indent=2, ensure_ascii=False)

print(open("shelf.json", encoding="utf-8").read())

with open("shelf.json", encoding="utf-8") as f:
    loaded = json.load(f)
print(len(loaded), loaded[1]["title"])
פלטOutput
[
  {
    "title": "Dune",
    "author": "Frank Herbert",
    "pages": 412
  },
  {
    "title": "הנסיך הקטן",
    "author": "Antoine de Saint-Exupéry",
    "pages": 96
  }
]
2 הנסיך הקטן
[
  {
    "title": "Dune",
    "author": "Frank Herbert",
    "pages": 412
  },
  {
    "title": "The Little Prince",
    "author": "Antoine de Saint-Exupéry",
    "pages": 96
  }
]
2 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

dump ו-load הם כמו לארוז מזוודה ולפרוק אותה: הבגדים יוצאים בדיוק באותו סדר ומבנה שבו נארזו.

dump and load are like packing and unpacking a suitcase: everything comes out in exactly the structure it went in.

טעות נפוצהCommon mistake

טוענים קובץ שעוד לא קיים בהרצה הראשונה.

Loading a file that doesn't exist yet on the first run.

load_json.py
import json
with open("shelf.json", encoding="utf-8") as f:
    shelf = json.load(f)
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/load_json.py", line 2, in <module>
    with open("shelf.json", encoding="utf-8") as f:
         ~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
FileNotFoundError: [Errno 2] No such file or directory: 'shelf.json'
בעברית פשוטה: In plain words: FileNotFoundError: [Errno 2] No such file or directory: 'shelf.json': בפעם הראשונה אין קובץ. בודקים קודם עם Path("shelf.json").exists() ומתחילים מרשימה ריקה.FileNotFoundError: [Errno 2] No such file or directory: 'shelf.json': on the first run there's no file. Check Path("shelf.json").exists() first and start from an empty list.

03מה JSON יודע לשמורWhat JSON can store

JSON יודע רק את הטיפוסים הבסיסיים. set, תאריך או אובייקט של מחלקה שלכם, צריך להמיר קודם: set לרשימה, תאריך למחרוזת עם isoformat(), ו-dataclass למילון עם asdict (מפגש 18). עוד הפתעה: מפתחות של מילון ב-JSON הם תמיד מחרוזות.

JSON knows only the basic types. A set, a date or an object of your own class must be converted first: a set to a list, a date to a string with isoformat(), and a dataclass to a dict with asdict (session 18). One more surprise: dictionary keys in JSON are always strings.

type_demo.py
import json
from dataclasses import dataclass, asdict
from datetime import date

@dataclass
class Book:
    title: str
    pages: int

data = {"book": asdict(Book("Dune", 412)), "tags": sorted({"sci-fi", "classic"}),
        "added": date(2026, 3, 1).isoformat(), 1: "one"}
text = json.dumps(data)
print(text)
print(json.loads(text).keys())
פלטOutput
{"book": {"title": "Dune", "pages": 412}, "tags": ["classic", "sci-fi"], "added": "2026-03-01", "1": "one"}
dict_keys(['book', 'tags', 'added', '1'])
צפו בהרצה צעד אחר צעד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

JSON הוא כמו מעטפה בדואר: אפשר לשלוח בה דף, אבל לא עוגה. את העוגה צריך קודם להפוך למתכון.

JSON is like a postal envelope: you can send a page in it, not a cake. The cake must first become a recipe.

טעות נפוצהCommon mistake

מנסים לשמור set ישירות.

Trying to save a set directly.

type_demo.py
import json
print(json.dumps({"tags": {"sci-fi", "classic"}}))
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/type_demo.py", line 2, in <module>
    print(json.dumps({"tags": {"sci-fi", "classic"}}))
          ~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.13/json/__init__.py", line 235, in dumps
    return _default_encoder.encode(obj)
           ~~~~~~~~~~~~~~~~~~~~~~~^^^^^
  File "/usr/local/lib/python3.13/json/encoder.py", line 202, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/usr/local/lib/python3.13/json/encoder.py", line 263, in iterencode
    return _iterencode(o, 0)
  File "/usr/local/lib/python3.13/json/encoder.py", line 182, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
                    f'is not JSON serializable')
TypeError: Object of type set is not JSON serializable
בעברית פשוטה: In plain words: TypeError: Object of type set is not JSON serializable: ממירים לרשימה: sorted(tags) (או list(tags)).TypeError: Object of type set is not JSON serializable: convert to a list: sorted(tags) (or list(tags)).
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

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

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

מסך הפלטOutput screen

04CSV: טבלאות בטקסטCSV: tables in text

CSV הוא הפורמט של גיליונות: כל שורה רשומה, ופסיקים בין הערכים. אל תפצלו בעצמכם עם split(","), כי ערך יכול להכיל פסיק (בתוך מירכאות). המודול csv מטפל בזה. DictReader משתמש בשורת הכותרות ונותן מילון לכל שורה. שימו לב: כל הערכים מגיעים כמחרוזות.

CSV is the spreadsheet format: each line a record, commas between values. Don't split it yourself with split(","), because a value can contain a comma (inside quotes). The csv module handles that. DictReader uses the header row and gives a dict per row. Note: every value arrives as a string.

read_csv.py
import csv

with open("books.csv", "w", encoding="utf-8") as f:
    f.write('title,author,pages\nDune,Frank Herbert,412\n"Matilda, special edition",Roald Dahl,240\n')

with open("books.csv", encoding="utf-8", newline="") as f:
    rows = list(csv.DictReader(f))

for r in rows:
    print(r["title"], "|", r["pages"], type(r["pages"]).__name__)
print(sum(int(r["pages"]) for r in rows))
פלטOutput
Dune | 412 str
Matilda, special edition | 240 str
652
צפו בהרצה צעד אחר צעד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

CSV הוא כמו טבלה שמישהו הכתיב בטלפון: "שם פסיק סופר פסיק עמודים". המודול csv יודע לרשום אותה בחזרה לעמודות.

CSV is like a table dictated over the phone: "title comma author comma pages". The csv module knows how to write it back into columns.

טעות נפוצהCommon mistake

מחברים מספרים שנקראו מ-CSV בלי להמיר.

Adding numbers read from CSV without converting.

read_csv.py
import csv, io
rows = csv.DictReader(io.StringIO("title,pages\nDune,412\nEmma,474\n"))
print(sum(r["pages"] for r in rows))
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/read_csv.py", line 3, in <module>
    print(sum(r["pages"] for r in rows))
          ~~~^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: unsupported operand type(s) for +: 'int' and 'str'
בעברית פשוטה: In plain words: TypeError: unsupported operand type(s) for +: 'int' and 'str': הערכים הם מחרוזות. ממירים: int(r["pages"]).TypeError: unsupported operand type(s) for +: 'int' and 'str': the values are strings. Convert: int(r["pages"]).
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

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

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

מסך הפלטOutput screen

05לכתוב CSVWriting CSV

DictWriter כותב רשימת מילונים לטבלה. קובעים את סדר העמודות ב-fieldnames, כותבים כותרות, ואז את השורות. פותחים את הקובץ עם newline="", אחרת ב-Windows תופיע שורה ריקה בין כל שתי שורות. מכאן אפשר לפתוח את הקובץ באקסל.

DictWriter writes a list of dicts as a table. Set the column order in fieldnames, write the headers, then the rows. Open the file with newline="", otherwise Windows gets a blank line between rows. You can then open the file in Excel.

write_csv.py
import csv

shelf = [{"title": "Dune", "author": "Frank Herbert", "pages": 412, "read": True},
         {"title": "Emma", "author": "Jane Austen", "pages": 474, "read": False}]

with open("export.csv", "w", encoding="utf-8", newline="") as f:
    w = csv.DictWriter(f, fieldnames=["title", "author", "pages", "read"])
    w.writeheader()
    w.writerows(shelf)

print(open("export.csv", encoding="utf-8").read())
פלטOutput
title,author,pages,read
Dune,Frank Herbert,412,True
Emma,Jane Austen,474,False
צפו בהרצה צעד אחר צעד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

DictWriter הוא כמו מזכיר שממלא טופס: אתם אומרים לו מה הכותרות, ומוסרים לו את הנתונים, והוא מסדר הכול בעמודות.

DictWriter is like a clerk filling in a form: you tell them the headings, hand over the data, and they line it up in columns.

טעות נפוצהCommon mistake

במילון יש מפתח שלא מופיע ב-fieldnames.

A dict has a key that isn't in fieldnames.

write_csv.py
import csv, io
w = csv.DictWriter(io.StringIO(), fieldnames=["title"])
w.writerow({"title": "Dune", "pages": 412})
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/write_csv.py", line 3, in <module>
    w.writerow({"title": "Dune", "pages": 412})
    ~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.13/csv.py", line 226, in writerow
    return self.writer.writerow(self._dict_to_list(rowdict))
                                ~~~~~~~~~~~~~~~~~~^^^^^^^^^
  File "/usr/local/lib/python3.13/csv.py", line 221, in _dict_to_list
    raise ValueError("dict contains fields not in fieldnames: "
                     + ", ".join([repr(x) for x in wrong_fields]))
ValueError: dict contains fields not in fieldnames: 'pages'
בעברית פשוטה: In plain words: ValueError: dict contains fields not in fieldnames: 'pages': מוסיפים את העמודה ל-fieldnames, או extrasaction="ignore" כדי לדלג על מפתחות נוספים.ValueError: dict contains fields not in fieldnames: 'pages': add the column to fieldnames, or extrasaction="ignore" to skip extra keys.
צפו איפה זה נשבר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קבצים פגומיםBroken files

קבצים נשברים: מישהו ערך ביד ושכח פסיק, או שהתוכנית נעצרה באמצע כתיבה. טוענים בתוך try ותופסים json.JSONDecodeError עם הודעה ברורה. ובשמירה: כותבים קודם לקובץ זמני ורק אז מחליפים עם Path.replace, כך שקריסה באמצע לעולם לא תשאיר קובץ חצוי.

Files break: someone edited by hand and forgot a comma, or the program stopped mid-write. Load inside try and catch json.JSONDecodeError with a clear message. When saving: write to a temporary file first and only then swap with Path.replace, so a crash midway never leaves a half-written file.

robust.py
import json
from pathlib import Path

def load(path):
    p = Path(path)
    if not p.exists():
        return []
    try:
        return json.loads(p.read_text(encoding="utf-8"))
    except json.JSONDecodeError as e:
        print(f"הקובץ פגום בשורה {e.lineno}: {e.msg}")
        return []

def save(path, data):
    tmp = Path(path + ".tmp")
    tmp.write_text(json.dumps(data, indent=2, ensure_ascii=False), encoding="utf-8")
    tmp.replace(path)

save("shelf.json", [{"title": "Dune"}])
print(load("shelf.json"))
Path("shelf.json").write_text('[{"title": "Dune",}]', encoding="utf-8")
print(load("shelf.json"))
import json
from pathlib import Path

def load(path):
    p = Path(path)
    if not p.exists():
        return []
    try:
        return json.loads(p.read_text(encoding="utf-8"))
    except json.JSONDecodeError as e:
        print(f"the file is broken at line {e.lineno}: {e.msg}")
        return []

def save(path, data):
    tmp = Path(path + ".tmp")
    tmp.write_text(json.dumps(data, indent=2, ensure_ascii=False), encoding="utf-8")
    tmp.replace(path)

save("shelf.json", [{"title": "Dune"}])
print(load("shelf.json"))
Path("shelf.json").write_text('[{"title": "Dune",}]', encoding="utf-8")
print(load("shelf.json"))
פלטOutput
[{'title': 'Dune'}]
הקובץ פגום בשורה 1: Illegal trailing comma before end of object
[]
[{'title': 'Dune'}]
the file is broken at line 1: Illegal trailing comma before end of object
[]
צפו בהרצה צעד אחר צעד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

לכתוב לקובץ זמני ואז להחליף זה כמו לצבוע חדר: מכינים את הצבע החדש לגמרי בדלי, ורק כשהוא מוכן מתחילים לצבוע, ולא מערבבים על הקיר.

Writing to a temp file then swapping is like painting a room: mix the new colour fully in the bucket, and only when it's ready start painting, not mixing on the wall.

טעות נפוצהCommon mistake

פסיק מיותר בסוף, טעות קלאסית בעריכה ידנית.

A trailing comma, a classic hand-editing mistake.

robust.py
import json
json.loads('{"title": "Dune", "pages": 412,}')
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/robust.py", line 2, in <module>
    json.loads('{"title": "Dune", "pages": 412,}')
    ~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.13/json/__init__.py", line 352, in loads
    return _default_decoder.decode(s)
           ~~~~~~~~~~~~~~~~~~~~~~~^^^
  File "/usr/local/lib/python3.13/json/decoder.py", line 345, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
               ~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.13/json/decoder.py", line 361, in raw_decode
    obj, end = self.scan_once(s, idx)
               ~~~~~~~~~~~~~~^^^^^^^^
json.decoder.JSONDecodeError: Illegal trailing comma before end of object: line 1 column 31 (char 30)
בעברית פשוטה: In plain words: json.decoder.JSONDecodeError: Illegal trailing comma before end of object: line 1 column 30 (char 29): JSON לא מרשה פסיק אחרי האיבר האחרון. מוחקים אותו.json.decoder.JSONDecodeError: Illegal trailing comma before end of object: line 1 column 30 (char 29): JSON doesn't allow a comma after the last item. Delete it.
צפו איפה זה נשבר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