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

חזרה למפגשBack
PythonPython

JSON ו-CSVJSON & CSV

מפגש 21: שמירה בפורמטים מקובלים, ייבוא וייצוא.Session 21: Saving in standard formats, import and export.

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

  • JSONJSON
  • קבציםFiles
  • טיפוסיםTypes
  • CSVCSV
  • כתיבהWriting
  • עמידותRobustness
נושאTopic 1

JSONJSON

מה זה JSON?What is JSON?

  • נראה כמעט כמו מילון של פייתוןLooks almost like a Python dict
  • true/false/null במקום True/False/Nonetrue/false/null instead of True/False/None
  • מירכאות כפולות בלבדDouble quotes only

אנלוגיה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_demo.py
import json
print(json.loads("{'title': 'Dune'}"))
מה Python עונהWhat Python says
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
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.
נושאTopic 2

קבציםFiles

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

  • json.dump(data, f) כותב לקובץjson.dump(data, f) writes to a file
  • json.load(f) קורא מקובץjson.load(f) reads from a file
  • indent=2, ensure_ascii=False לקובץ קריא בעבריתindent=2, ensure_ascii=False for a readable file in Hebrew

אנלוגיהAnalogy

dump ו-load הם כמו לארוז מזוודה ולפרוק אותה: הבגדים יוצאים בדיוק באותו סדר ומבנה שבו נארזו.dump and load are like packing and unpacking a suitcase: everything comes out in exactly the structure it went in.
נושאTopic 3

טיפוסיםTypes

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

  • dict, list, str, int, float, bool, Nonedict, list, str, int, float, bool, None
  • לא set, לא תאריך, לא אובייקטNo set, no date, no object
  • ממירים קודם: list(s), asdict(b), d.isoformat()Convert first: list(s), asdict(b), d.isoformat()

אנלוגיה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.
נושאTopic 4

CSVCSV

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

  • שורה ראשונה: כותרותFirst line: headers
  • csv.DictReader → מילון לכל שורהcsv.DictReader → a dict per row
  • כל ערך נקרא כמחרוזת!Every value is read as a string!

אנלוגיה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.
נושאTopic 5

כתיבהWriting

לכתוב CSVWriting CSV

  • csv.DictWriter(f, fieldnames=[...])csv.DictWriter(f, fieldnames=[...])
  • writeheader() ואז writerows(rows)writeheader() then writerows(rows)
  • newline="" מונע שורות ריקות ב-Windowsnewline="" prevents blank lines on Windows

אנלוגיה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.
נושאTopic 6

עמידותRobustness

קבצים פגומיםBroken files

  • json.JSONDecodeError לקובץ שבורjson.JSONDecodeError for a broken file
  • גיבוי לפני דריסהBack up before overwriting
  • כתיבה לקובץ זמני ואז החלפהWrite to a temp file, then replace

אנלוגיה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.

נראה כמעט כמו מילון של פייתוןLooks almost like a Python dict

true/false/null במקום True/False/Nonetrue/false/null instead of True/False/None

מירכאות כפולות בלבדDouble quotes only

json.dump(data, f) כותב לקובץjson.dump(data, f) writes to a file

json.load(f) קורא מקובץjson.load(f) reads from a file

indent=2, ensure_ascii=False לקובץ קריא בעבריתindent=2, ensure_ascii=False for a readable file in Hebrew

dict, list, str, int, float, bool, Nonedict, list, str, int, float, bool, None

לא set, לא תאריך, לא אובייקטNo set, no date, no object

ממירים קודם: list(s), asdict(b), d.isoformat()Convert first: list(s), asdict(b), d.isoformat()

שורה ראשונה: כותרותFirst line: headers

csv.DictReader → מילון לכל שורהcsv.DictReader → a dict per row

כל ערך נקרא כמחרוזת!Every value is read as a string!

csv.DictWriter(f, fieldnames=[...])csv.DictWriter(f, fieldnames=[...])

writeheader() ואז writerows(rows)writeheader() then writerows(rows)

newline="" מונע שורות ריקות ב-Windowsnewline="" prevents blank lines on Windows

json.JSONDecodeError לקובץ שבורjson.JSONDecodeError for a broken file

גיבוי לפני דריסהBack up before overwriting

מה למדנוWhat we learned

  • נראה כמעט כמו מילון של פייתוןLooks almost like a Python dict
  • json.dump(data, f) כותב לקובץjson.dump(data, f) writes to a file
  • dict, list, str, int, float, bool, Nonedict, list, str, int, float, bool, None
  • שורה ראשונה: כותרותFirst line: headers
  • csv.DictWriter(f, fieldnames=[...])csv.DictWriter(f, fieldnames=[...])
  • json.JSONDecodeError לקובץ שבורjson.JSONDecodeError for a broken file

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

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

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