الفلاتر
طريقة البحث
  • الكلمات العادية تجد الأسماء والنصوص والأمثلة.
  • "كلمتان" تجد العبارة بالضبط.
  • --name أو -x تجد خيارًا.
  • #كلمة تبحث داخل الأوامر فقط.
  • @grep تجد الدروس والمعامل التي تستخدم grep.
  • الفلاتر: cat:network · in:labs · level:rhcsa · ch:8 · root:yes. ضع ! قبل كلمة لاستبعادها. OR بين الكلمات تعني إحداها.
  • ↑ ↓ للتنقل · Enter للفتح · Esc للإغلاق · / للبحث

الفصل 5الاسم في الدورة: Data formats

Read and write CSV, JSON and YAML

Admins move data between tools: CSV for spreadsheets and user lists, JSON for APIs and kubectl -o json, YAML for Kubernetes, Ansible and CI. Python reads and writes all three.

  • 4 الدروس
  • 0 الأوامر

هذا الجزء لم يُترجم بعد. أنت ترى النص الإنجليزي.

$ مستخدم عادي# بصلاحية root (أو مع sudo)

5.1

Read and write CSV

csv.DictReader gives each row as a dict with the header names.

users_csv.py
import csv
 
with open("new_users.csv", newline="", encoding="utf-8") as f:
    for row in csv.DictReader(f):
        print(row["username"], row["department"])
 
rows = [{"host": "web1", "status": "ok"}, {"host": "db1", "status": "down"}]
with open("report.csv", "w", newline="", encoding="utf-8") as f:
    writer = csv.DictWriter(f, fieldnames=["host", "status"])
    writer.writeheader()
    writer.writerows(rows)

5.2

Read and write JSON

json.loads turns text into dicts and lists; json.dumps does the opposite.

pods_json.py
import json
import subprocess
 
out = subprocess.run(["kubectl", "get", "pods", "-A", "-o", "json"], capture_output=True, text=True, check=True).stdout
data = json.loads(out)
for pod in data["items"]:
    ns = pod["metadata"]["namespace"]
    name = pod["metadata"]["name"]
    phase = pod["status"]["phase"]
    if phase != "Running":
        print(f"{ns}/{name}: {phase}")
 
with open("summary.json", "w", encoding="utf-8") as f:
    json.dump({"checked": len(data["items"])}, f, indent=2)

5.3

Read and write YAML

Use PyYAML (pip install pyyaml) with safe_load — never plain load on files you do not trust.

yaml_edit.py
import yaml
 
with open("deployment.yaml", encoding="utf-8") as f:
    docs = list(yaml.safe_load_all(f))
 
for d in docs:
    if d and d.get("kind") == "Deployment":
        d["spec"]["replicas"] = 3
        for c in d["spec"]["template"]["spec"]["containers"]:
            c.setdefault("resources", {"limits": {"memory": "512Mi"}})
 
with open("deployment.out.yaml", "w", encoding="utf-8") as f:
    yaml.safe_dump_all(docs, f, sort_keys=False)

انتبه

yaml.load without a safe loader can run code from the file. Always safe_load.

5.4

Use TOML and INI

Python reads TOML (tomllib, built in since 3.11) and INI (configparser) config files.

config_read.py
import configparser
import tomllib
 
with open("pyproject.toml", "rb") as f:
    print(tomllib.load(f)["project"]["name"])
 
ini = configparser.ConfigParser()
ini.read("/etc/dnf/dnf.conf")
print(ini.get("main", "installonly_limit", fallback="3"))