Skip to content

Latest commit

 

History

History
271 lines (169 loc) · 5.24 KB

2.2.md

File metadata and controls

271 lines (169 loc) · 5.24 KB

JSON i CSV / JSON and CSV


JSON — structured data / JSON — dane strukturyzowane

Documentation:

Python json module

Video:

Corey Schafer — Working with JSON Data (0:00–15:00)


Create json_demo.py:

Utwórz json_demo.py:

import json
from pathlib import Path

# Python dict / Słownik Pythona
person = {
    "name": "Alice",
    "age": 25,
    "hobbies": ["reading", "coding"]
}

# Save to JSON / Zapisz do JSON
Path("person.json").write_text(json.dumps(person, indent=2))
print("Saved to person.json")

# Load from JSON / Wczytaj z JSON
loaded = json.loads(Path("person.json").read_text())
print(f"Name: {loaded['name']}, Age: {loaded['age']}")

Run:

Uruchom:

uv run python json_demo.py

Check person.json — it's human-readable!

Sprawdź person.json — jest czytelny dla ludzi!


CSV — tables / CSV — tabele

CSV (Comma-Separated Values) is like Excel saved as text.

CSV (wartości rozdzielane przecinkami) to jak Excel zapisany jako tekst.

Documentation:

Python csv module

Video:

Corey Schafer — Reading and Writing CSV Files (0:00–18:00)


Create csv_demo.py:

Utwórz csv_demo.py:

import csv

# Write CSV / Pisz CSV
with open("products.csv", "w", newline="") as file:
    writer = csv.writer(file)
    writer.writerow(["Name", "Price", "Stock"])
    writer.writerow(["Laptop", 999.99, 15])
    writer.writerow(["Mouse", 29.99, 50])

print("Created products.csv")

# Read CSV / Czytaj CSV
with open("products.csv", "r") as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)

Run:

Uruchom:

uv run python csv_demo.py

DictReader / DictWriter — easier way / łatwiejszy sposób

Working with dictionaries is cleaner than lists.

Praca ze słownikami jest czystsza niż z listami.

import csv

# Write with DictWriter / Pisz z DictWriter
employees = [
    {"name": "Alice", "salary": 70000},
    {"name": "Bob", "salary": 60000}
]

with open("employees.csv", "w", newline="") as file:
    writer = csv.DictWriter(file, fieldnames=["name", "salary"])
    writer.writeheader()
    writer.writerows(employees)

# Read with DictReader / Czytaj z DictReader
with open("employees.csv", "r") as file:
    reader = csv.DictReader(file)
    for row in reader:
        print(f"{row['name']}: ${row['salary']}")

Real-world example: save user data / Przykład z życia: zapisywanie danych użytkownika

This is how I save app settings in my projects.

Tak zapisuję ustawienia aplikacji w moich projektach.

Create user_settings.py:

Utwórz user_settings.py:

import json
from pathlib import Path

class UserSettings:
    def __init__(self, settings_file: str = "settings.json"):
        self.file = Path(settings_file)
        self.settings = self.load()

    def load(self) -> dict:
        if self.file.exists():
            return json.loads(self.file.read_text())
        return {"theme": "light", "language": "en"}

    def save(self) -> None:
        self.file.write_text(json.dumps(self.settings, indent=2))

    def get(self, key: str, default=None):
        return self.settings.get(key, default)

    def set(self, key: str, value) -> None:
        self.settings[key] = value
        self.save()

# Usage / Użycie
settings = UserSettings()
print(f"Theme: {settings.get('theme')}")

settings.set("theme", "dark")
print(f"Updated theme: {settings.get('theme')}")

Run:

Uruchom:

uv run python user_settings.py

When to use what? / Kiedy czego użyć?

Use JSON when / Użyj JSON gdy:

  • Data has nested structure (objects within objects)

    Dane mają zagnieżdżoną strukturę (obiekty w obiektach)

  • Working with APIs (most use JSON)

    Pracujesz z API (większość używa JSON)

Use CSV when / Użyj CSV gdy:

  • Data is flat table

    Dane to płaska tabela

  • Sharing with Excel users

    Dzielisz się z użytkownikami Excel


Bonus: pandas for data work / Bonus: pandas do pracy z danymi

For serious data work, pandas makes everything easier.

Do poważnej pracy z danymi, pandas ułatwia wszystko.

Install:

Zainstaluj:

uv add pandas

Example:

Przykład:

import pandas as pd

# Read CSV / Czytaj CSV
df = pd.read_csv("employees.csv")

# Filter / Filtruj
high_earners = df[df["salary"] > 65000]
print(high_earners)

# Save to JSON / Zapisz do JSON
df.to_json("employees.json", orient="records", indent=2)

Podsumowanie / Summary

After this section you can:

Po tej sekcji potrafisz:

  • save and load JSON data

    zapisywać i wczytywać dane JSON

  • work with CSV files

    pracować z plikami CSV

  • use DictReader/DictWriter for cleaner code

    używać DictReader/DictWriter dla czystszego kodu

  • choose between JSON and CSV based on needs

    wybierać między JSON a CSV według potrzeb

  • optionally use pandas for data analysis

    opcjonalnie używać pandas do analizy danych


Next: 2.3 — Obsługa wyjątków