נבנה על ידי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.

או Ctrl+Por Ctrl+P

הנקודות החשובותKey points

  • נראה כמעט כמו מילון של פייתוןLooks almost like a Python dict
  • true/false/null במקום True/False/Nonetrue/false/null instead of True/False/None
  • json.dump(data, f) כותב לקובץjson.dump(data, f) writes to a file
  • json.load(f) קורא מקובץjson.load(f) reads from a file
  • dict, list, str, int, float, bool, Nonedict, list, str, int, float, bool, None
  • לא set, לא תאריך, לא אובייקטNo set, no date, no object
  • שורה ראשונה: כותרותFirst line: headers
  • csv.DictReader → מילון לכל שורהcsv.DictReader → a dict per row
  • csv.DictWriter(f, fieldnames=[...])csv.DictWriter(f, fieldnames=[...])

מונחיםTerms

  • JSONJSON: פורמט טקסט לנתונים מובנים: מילונים, רשימות, מחרוזות, מספרים, true/false ו-null. כמעט כל אתר ו-API מדברים בו.A text format for structured data: objects, lists, strings, numbers, true/false and null. Almost every website and API speaks it.
  • CSVCSV: קובץ טבלה בטקסט פשוט: שורה לכל רשומה, ערכים מופרדים בפסיקים. נפתח באקסל ובגוגל שיטס.A table in plain text: one line per record, values separated by commas. Opens in Excel and Google Sheets.
  • סריאליזציהserialization: הפיכת אובייקט בזיכרון לטקסט (או בתים) שאפשר לשמור או לשלוח. ההפך: דה-סריאליזציה.Turning an in-memory object into text (or bytes) that can be saved or sent. The reverse: deserialization.
  • שורת כותרותheader row: השורה הראשונה בקובץ CSV, עם שמות העמודות.The first line of a CSV file, with the column names.

Cheatsheet

JSONJSON
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)
קבציםFiles
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)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)
טיפוסיםTypes
import json
from dataclasses import dataclass, asdict
from datetime import date

@dataclass
class Book:
    title: str
CSVCSV
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))
כתיבהWriting
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"])
עמידותRobustness
import json
from pathlib import Path

def load(path):
    p = Path(path)
    if not p.exists():
        return []

שגיאות שפגשנוErrors we met

שגיאהErrorמה זה אומרWhat it meansמה עושיםWhat to do
json.decoder.JSONDecodeErrorכותבים JSON עם מירכאות בודדות, כמו בפייתון.Writing JSON with single quotes, like in Python.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.
FileNotFoundErrorטוענים קובץ שעוד לא קיים בהרצה הראשונה.Loading a file that doesn't exist yet on the first run.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.
TypeErrorמנסים לשמור set ישירות.Trying to save a set directly.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)).
TypeErrorמחברים מספרים שנקראו מ-CSV בלי להמיר.Adding numbers read from CSV without converting.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"]).
ValueErrorבמילון יש מפתח שלא מופיע ב-fieldnames.A dict has a key that isn't in fieldnames.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.
json.decoder.JSONDecodeErrorפסיק מיותר בסוף, טעות קלאסית בעריכה ידנית.A trailing comma, a classic hand-editing mistake.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.

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