هذا الجزء لم يُترجم بعد. أنت ترى النص الإنجليزي.
$ مستخدم عادي# بصلاحية root (أو مع sudo)
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)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)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.
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"))