Kurs Python · Moduł 4: Dane, API i bazy danych
Formaty danych w dżungli
W tej lekcji9
Witaj w Module 4! Darwin tutaj z nowym rozdziałem naszej przygody.
Do tej pory poznałeś/aś Python od podstaw do zaawansowanego OOP. Teraz czas na przepływ danych - jak przechowywać, wymieniać i transportować informacje między systemami, jak zwierzęta komunikują się w dżungli!
W naturze zwierzęta przekazują informacje na różne sposoby - ptaki śpiewem, pszczoły tańcem, wilki wyciem. W świecie programowania używamy formatów danych - standardowych sposobów zapisu informacji!
Czym są formaty danych?
Format danych to ustandaryzowany sposób organizacji i zapisu informacji, który mogą odczytać różne systemy.
Analogia Safari: To jak uniwersalny język komunikacji - niezależnie czy jesteś biologiem z Polski, naukowcem z Japonii czy przewodnikiem z Kenii, wszyscy rozumiecie tabelę z danymi o populacji lwów!
Najpopularniejsze formaty:
- JSON - JavaScript Object Notation - najpopularniejszy w web API
- CSV - Comma-Separated Values - prosty, tabelaryczny
- XML - eXtensible Markup Language - strukturalny, rozbudowany
- YAML - YAML Ain't Markup Language - czytelny dla ludzi, konfiguracje
JSON - JavaScript Object Notation
JSON to najważniejszy format danych w świecie web - lekki, czytelny, uniwersalny!
Struktura JSON
{
"species": "Panthera leo",
"common_name": "Lew",
"population": 120,
"endangered": true,
"habitats": ["sawanna", "step"],
"last_observation": {
"date": "2024-01-15",
"location": "Serengeti",
"count": 12
}
}Typy danych w JSON:
"tekst"- string (zawsze w cudzysłowach)123,45.67- numbertrue,false- booleannull- brak wartości[1, 2, 3]- array (lista){"key": "value"}- object (słownik)
JSON w Pythonie - moduł json
Python ma wbudowany moduł json do pracy z tym formatem:
import json
# Python → JSON (serializacja)
species_data = {
"species": "Panthera leo",
"common_name": "Lew",
"population": 120,
"endangered": True,
"habitats": ["sawanna", "step"],
"last_observation": {
"date": "2024-01-15",
"location": "Serengeti",
"count": 12
}
}
# Konwersja do JSON string
json_string = json.dumps(species_data, indent=2)
print(json_string)
"""
{
"species": "Panthera leo",
"common_name": "Lew",
"population": 120,
"endangered": true,
"habitats": [
"sawanna",
"step"
],
"last_observation": {
"date": "2024-01-15",
"location": "Serengeti",
"count": 12
}
}
"""
# JSON → Python (deserializacja)
json_text = '{"species": "Loxodonta africana", "population": 450}'
python_dict = json.loads(json_text)
print(python_dict["species"]) # "Loxodonta africana"Zapis i odczyt plików JSON
import json
# Zapis do pliku
species_data = {
"species": "Panthera leo",
"population": 120,
"observations": [
{"date": "2024-01-15", "count": 12},
{"date": "2024-01-20", "count": 8}
]
}
with open("species_data.json", "w", encoding="utf-8") as file:
json.dump(species_data, file, indent=2, ensure_ascii=False)
# Odczyt z pliku
with open("species_data.json", "r", encoding="utf-8") as file:
loaded_data = json.load(file)
print(loaded_data["species"]) # "Panthera leo"Różnica:
json.dumps()/json.loads()- string (dumps = dump string)json.dump()/json.load()- plik
JSON i Python - mapowanie typów
| Python | JSON |
|---|---|
dict | object |
list, tuple | array |
str | string |
int, float | number |
True | true |
False | false |
None | null |
import json
# Python → JSON
python_data = {
"name": "Darwin",
"age": None,
"active": True,
"coordinates": (51.5, -0.1) # Tuple → array
}
json_str = json.dumps(python_data)
print(json_str)
# {"name": "Darwin", "age": null, "active": true, "coordinates": [51.5, -0.1]}Serializacja obiektów własnych klas
Domyślnie JSON nie obsługuje obiektów własnych klas - potrzebujesz custom encoder:
import json
from datetime import datetime
class Species:
def __init__(self, name, population, last_seen):
self.name = name
self.population = population
self.last_seen = last_seen # datetime object
def to_dict(self):
"""Konwersja do słownika"""
return {
"name": self.name,
"population": self.population,
"last_seen": self.last_seen.isoformat() # datetime → string
}
@classmethod
def from_dict(cls, data):
"""Odtworzenie z słownika"""
return cls(
name=data["name"],
population=data["population"],
last_seen=datetime.fromisoformat(data["last_seen"])
)
# Serializacja
lion = Species("Lew", 120, datetime.now())
json_data = json.dumps(lion.to_dict(), indent=2)
print(json_data)
# Deserializacja
loaded_dict = json.loads(json_data)
lion_restored = Species.from_dict(loaded_dict)
print(lion_restored.name) # "Lew"CSV - Comma-Separated Values
CSV to prosty format tabelaryczny - doskonały do arkuszy kalkulacyjnych i baz danych!
Struktura CSV
species,common_name,population,habitat
Panthera leo,Lew,120,sawanna
Loxodonta africana,Słoń,450,sawanna
Python regius,Pyton,85,dżungla
Gorilla gorilla,Goryl,230,lasCechy:
- Pierwszy wiersz = nagłówki kolumn
- Kolejne wiersze = dane
- Separator: przecinek (czasem średnik, tabulator)
CSV w Pythonie - moduł csv
import csv
# ZAPIS CSV
species_data = [
{"species": "Panthera leo", "common_name": "Lew", "population": 120},
{"species": "Loxodonta africana", "common_name": "Słoń", "population": 450},
{"species": "Python regius", "common_name": "Pyton", "population": 85}
]
with open("species.csv", "w", newline="", encoding="utf-8") as file:
fieldnames = ["species", "common_name", "population"]
writer = csv.DictWriter(file, fieldnames=fieldnames)
writer.writeheader() # Zapisz nagłówki
writer.writerows(species_data) # Zapisz wszystkie wiersze
# ODCZYT CSV
with open("species.csv", "r", encoding="utf-8") as file:
reader = csv.DictReader(file)
for row in reader:
print(f"{row['common_name']}: {row['population']} osobników")
# Lew: 120 osobników
# Słoń: 450 osobników
# Pyton: 85 osobnikówCSV z listami (nie słownikami)
import csv
# Zapis list
data = [
["species", "population", "endangered"],
["Panthera leo", 120, "True"],
["Loxodonta africana", 450, "True"]
]
with open("species_simple.csv", "w", newline="", encoding="utf-8") as file:
writer = csv.writer(file)
writer.writerows(data)
# Odczyt list
with open("species_simple.csv", "r", encoding="utf-8") as file:
reader = csv.reader(file)
headers = next(reader) # Pierwszy wiersz = nagłówki
for row in reader:
species, population, endangered = row
print(f"{species}: {population}")Różne separatory
import csv
# Separator: średnik (popularne w Polsce/Europie)
with open("data_pl.csv", "w", newline="", encoding="utf-8") as file:
writer = csv.writer(file, delimiter=";")
writer.writerow(["gatunek", "populacja"])
writer.writerow(["Lew", "120"])
# Separator: tabulator
with open("data_tab.tsv", "w", newline="", encoding="utf-8") as file:
writer = csv.writer(file, delimiter="\t")
writer.writerow(["species", "population"])
writer.writerow(["Lion", "120"])XML - eXtensible Markup Language
XML to rozbudowany, strukturalny format - używany w enterprise, konfiguracjach, wymianie danych między systemami.
Struktura XML
<?xml version="1.0" encoding="UTF-8"?>
<species_catalog>
<species endangered="true">
<scientific_name>Panthera leo</scientific_name>
<common_name>Lew</common_name>
<population>120</population>
<habitats>
<habitat>sawanna</habitat>
<habitat>step</habitat>
</habitats>
<observations>
<observation>
<date>2024-01-15</date>
<location>Serengeti</location>
<count>12</count>
</observation>
</observations>
</species>
</species_catalog>Cechy:
- Tagi hierarchiczne:
<tag>wartość</tag> - Atrybuty:
<tag attribute="value"> - Samozamykające:
<tag /> - Bardziej gadatliwy niż JSON
XML w Pythonie - moduł xml.etree.ElementTree
import xml.etree.ElementTree as ET
# TWORZENIE XML
root = ET.Element("species_catalog")
# Dodaj gatunek
species = ET.SubElement(root, "species")
species.set("endangered", "true") # Atrybut
ET.SubElement(species, "scientific_name").text = "Panthera leo"
ET.SubElement(species, "common_name").text = "Lew"
ET.SubElement(species, "population").text = "120"
# Habitats
habitats = ET.SubElement(species, "habitats")
ET.SubElement(habitats, "habitat").text = "sawanna"
ET.SubElement(habitats, "habitat").text = "step"
# Zapis do pliku
tree = ET.ElementTree(root)
ET.indent(tree, space=" ") # Python 3.9+ - formatowanie
tree.write("species.xml", encoding="utf-8", xml_declaration=True)
# ODCZYT XML
tree = ET.parse("species.xml")
root = tree.getroot()
for species in root.findall("species"):
name = species.find("common_name").text
population = species.find("population").text
endangered = species.get("endangered") # Atrybut
print(f"{name}: {population} osobników (zagrożony: {endangered})")
# Habitats
habitats = species.find("habitats")
for habitat in habitats.findall("habitat"):
print(f" - {habitat.text}")YAML - YAML Ain't Markup Language
YAML to czytelny dla ludzi format - popularny w konfiguracjach (Docker, Kubernetes, CI/CD)!
Struktura YAML
# Komentarz w YAML
species:
scientific_name: Panthera leo
common_name: Lew
population: 120
endangered: true
habitats:
- sawanna
- step
last_observation:
date: 2024-01-15
location: Serengeti
count: 12
# Lista gatunków
all_species:
- name: Lew
population: 120
- name: Słoń
population: 450
- name: Pyton
population: 85Cechy:
- Wcięcia określają hierarchię (jak Python!)
-oznacza element listykey: value- pary klucz-wartość- Bardzo czytelny
YAML w Pythonie - biblioteka PyYAML
import yaml
# Instalacja: pip install pyyaml
# Python → YAML
species_data = {
"species": "Panthera leo",
"common_name": "Lew",
"population": 120,
"endangered": True,
"habitats": ["sawanna", "step"],
"last_observation": {
"date": "2024-01-15",
"location": "Serengeti",
"count": 12
}
}
# Konwersja do YAML string
yaml_string = yaml.dump(species_data, default_flow_style=False, allow_unicode=True)
print(yaml_string)
# YAML → Python
yaml_text = """
species: Loxodonta africana
population: 450
endangered: true
"""
python_dict = yaml.safe_load(yaml_text)
print(python_dict["species"]) # "Loxodonta africana"
# Zapis/odczyt plików
with open("config.yaml", "w", encoding="utf-8") as file:
yaml.dump(species_data, file, default_flow_style=False, allow_unicode=True)
with open("config.yaml", "r", encoding="utf-8") as file:
loaded_data = yaml.safe_load(file)Safari przykład - kompletny system zarządzania danymi
import json
import csv
import xml.etree.ElementTree as ET
from datetime import datetime
from typing import List, Dict, Any
class Species:
"""Klasa gatunku z eksportem do różnych formatów"""
def __init__(self, scientific_name: str, common_name: str,
population: int, habitat: str, endangered: bool = False):
self.scientific_name = scientific_name
self.common_name = common_name
self.population = population
self.habitat = habitat
self.endangered = endangered
self.observations: List[Dict[str, Any]] = []
def add_observation(self, date: str, location: str, count: int):
"""Dodaj obserwację"""
self.observations.append({
"date": date,
"location": location,
"count": count
})
# === EKSPORT DO JSON ===
def to_json_dict(self) -> dict:
"""Konwersja do słownika dla JSON"""
return {
"scientific_name": self.scientific_name,
"common_name": self.common_name,
"population": self.population,
"habitat": self.habitat,
"endangered": self.endangered,
"observations": self.observations
}
@classmethod
def from_json_dict(cls, data: dict) -> 'Species':
"""Odtworzenie z słownika JSON"""
species = cls(
scientific_name=data["scientific_name"],
common_name=data["common_name"],
population=data["population"],
habitat=data["habitat"],
endangered=data.get("endangered", False)
)
species.observations = data.get("observations", [])
return species
# === EKSPORT DO CSV ===
def to_csv_row(self) -> dict:
"""Konwersja do wiersza CSV (uproszczone - bez obserwacji)"""
return {
"scientific_name": self.scientific_name,
"common_name": self.common_name,
"population": self.population,
"habitat": self.habitat,
"endangered": "Yes" if self.endangered else "No"
}
# === EKSPORT DO XML ===
def to_xml_element(self) -> ET.Element:
"""Konwersja do elementu XML"""
species_elem = ET.Element("species")
species_elem.set("endangered", str(self.endangered).lower())
ET.SubElement(species_elem, "scientific_name").text = self.scientific_name
ET.SubElement(species_elem, "common_name").text = self.common_name
ET.SubElement(species_elem, "population").text = str(self.population)
ET.SubElement(species_elem, "habitat").text = self.habitat
# Observations
if self.observations:
obs_elem = ET.SubElement(species_elem, "observations")
for obs in self.observations:
obs_item = ET.SubElement(obs_elem, "observation")
ET.SubElement(obs_item, "date").text = obs["date"]
ET.SubElement(obs_item, "location").text = obs["location"]
ET.SubElement(obs_item, "count").text = str(obs["count"])
return species_elem
def __repr__(self) -> str:
return f"Species('{self.common_name}', pop={self.population})"
class SpeciesDatabase:
"""Baza danych gatunków z eksportem do różnych formatów"""
def __init__(self):
self.species: List[Species] = []
def add_species(self, species: Species):
"""Dodaj gatunek"""
self.species.append(species)
# === JSON ===
def export_json(self, filename: str):
"""Eksport do JSON"""
data = {
"export_date": datetime.now().isoformat(),
"species_count": len(self.species),
"species": [s.to_json_dict() for s in self.species]
}
with open(filename, "w", encoding="utf-8") as file:
json.dump(data, file, indent=2, ensure_ascii=False)
print(f"Wyeksportowano {len(self.species)} gatunków do {filename}")
def import_json(self, filename: str):
"""Import z JSON"""
with open(filename, "r", encoding="utf-8") as file:
data = json.load(file)
self.species.clear()
for species_data in data["species"]:
self.species.append(Species.from_json_dict(species_data))
print(f"Zaimportowano {len(self.species)} gatunków z {filename}")
# === CSV ===
def export_csv(self, filename: str):
"""Eksport do CSV"""
if not self.species:
print("Brak gatunków do eksportu")
return
fieldnames = ["scientific_name", "common_name", "population", "habitat", "endangered"]
with open(filename, "w", newline="", encoding="utf-8") as file:
writer = csv.DictWriter(file, fieldnames=fieldnames)
writer.writeheader()
for species in self.species:
writer.writerow(species.to_csv_row())
print(f"Wyeksportowano {len(self.species)} gatunków do {filename}")
def import_csv(self, filename: str):
"""Import z CSV"""
self.species.clear()
with open(filename, "r", encoding="utf-8") as file:
reader = csv.DictReader(file)
for row in reader:
species = Species(
scientific_name=row["scientific_name"],
common_name=row["common_name"],
population=int(row["population"]),
habitat=row["habitat"],
endangered=(row["endangered"].lower() == "yes")
)
self.species.append(species)
print(f"Zaimportowano {len(self.species)} gatunków z {filename}")
# === XML ===
def export_xml(self, filename: str):
"""Eksport do XML"""
root = ET.Element("species_database")
root.set("export_date", datetime.now().isoformat())
root.set("species_count", str(len(self.species)))
for species in self.species:
root.append(species.to_xml_element())
tree = ET.ElementTree(root)
ET.indent(tree, space=" ")
tree.write(filename, encoding="utf-8", xml_declaration=True)
print(f"Wyeksportowano {len(self.species)} gatunków do {filename}")
def list_species(self):
"""Wyświetl wszystkie gatunki"""
print(f"\n=== BAZA GATUNKÓW ({len(self.species)}) ===")
for i, species in enumerate(self.species, 1):
status = "Zagrożony" if species.endangered else "Bezpieczny"
print(f"{i}. {species.common_name} ({species.scientific_name})")
print(f" Populacja: {species.population}, Siedlisko: {species.habitat}, Status: {status}")
# === DEMONSTRACJA ===
print("=== SYSTEM ZARZĄDZANIA DANYMI SAFARI ===\n")
# Tworzenie bazy danych
db = SpeciesDatabase()
# Dodaj gatunki
lion = Species("Panthera leo", "Lew", 120, "sawanna", endangered=True)
lion.add_observation("2024-01-15", "Serengeti", 12)
lion.add_observation("2024-01-20", "Masai Mara", 8)
elephant = Species("Loxodonta africana", "Słoń afrykański", 450, "sawanna", endangered=True)
elephant.add_observation("2024-01-16", "Amboseli", 35)
python_snake = Species("Python regius", "Pyton królewski", 85, "dżungla", endangered=False)
db.add_species(lion)
db.add_species(elephant)
db.add_species(python_snake)
# Wyświetl dane
db.list_species()
# EKSPORT do różnych formatów
print("\n=== EKSPORT ===")
db.export_json("safari_data.json")
db.export_csv("safari_data.csv")
db.export_xml("safari_data.xml")
# IMPORT z JSON
print("\n=== IMPORT Z JSON ===")
db2 = SpeciesDatabase()
db2.import_json("safari_data.json")
db2.list_species()
# IMPORT z CSV
print("\n=== IMPORT Z CSV ===")
db3 = SpeciesDatabase()
db3.import_csv("safari_data.csv")
db3.list_species()
print("\nWszystkie formaty działają!")Porównanie formatów
| Format | Zalety | Wady | Użycie |
|---|---|---|---|
| JSON | Lekki, czytelny, uniwersalny w web | Brak komentarzy | Web API, konfiguracje, wymiana danych |
| CSV | Prosty, excel-friendly, mało miejsca | Tylko tabele, brak hierarchii | Dane tabelaryczne, eksport/import do arkuszy |
| XML | Strukturalny, walidacja schematami | Gadatliwy, trudniejszy | Enterprise, SOAP, legacy systems |
| YAML | Bardzo czytelny, komentarze | Wrażliwy na wcięcia | Konfiguracje (Docker, K8s, CI/CD) |
Podsumowanie
W tej lekcji nauczyłeś/aś się:
- Czym są formaty danych i po co ich używać
- JSON -
json.dumps(),json.loads(),json.dump(),json.load() - CSV -
csv.DictWriter,csv.DictReader, różne separatory - XML -
xml.etree.ElementTree, tworzenie i parsowanie - YAML -
yaml.dump(),yaml.safe_load(), czytelność - Konwersji obiektów między formatami
- Praktycznego systemu eksportu/importu danych
Checkpoint
Przed przejściem dalej:
- Potrafisz zapisać i odczytać JSON
- Rozumiesz różnicę między
dumpsadump - Potrafisz pracować z CSV (DictWriter/DictReader)
- Wiesz kiedy używać którego formatu
- Potrafisz konwertować obiekty do słowników
Analogia Safari: Formaty danych to uniwersalne języki komunikacji - jak biologowie z różnych krajów używają łacińskich nazw gatunków, programiści używają JSON/CSV/XML do wymiany danych!
W następnej lekcji Darwin nauczy Cię HTTP i requests - jak pobierać dane z internetu i komunikować się z API!
Hasła z dokumentacji w tej lekcji
Widzisz błąd w tej lekcji?
Sprawdź się
Odpowiedz na pytania z tej lekcji. Wybierz odpowiedź, a od razu zobaczysz, czy jest poprawna.
1. JSON to skrót od:
2. Która funkcja konwertuje słownik Python na string JSON?
To 2 z 4 pytań do tej lekcji. Pozostałe rozwiążesz w grze.
Zadania praktyczne w grze
- Układanie w pionie
Uporządkuj kroki odczytu JSON:
- Edytor kodu
Zapisz słownik animal = {'name': 'Tygrys', 'weight': 200} do pliku 'animal.json'
- Edytor kodu
Odczytaj plik 'animals.csv' i wypisz wszystkie wiersze
- Układanie w poziomie
Uporządkuj: json.dumps(data, indent=2)
- Klikanie w kolejności
Kliknij w kolejności: with open('file.json', 'w') as f:
- Układanie w pionie
Uporządkuj kroki zapisu JSON: