12. Entrées-Sorties

Fichiers, with, modes, json, csv, pathlib, tempfile.


12.1 open() et modes

f = open("fichier.txt", "r")   # lecture (texte, défaut)
f = open("fichier.txt", "w")   # écriture (écrase)
f = open("fichier.txt", "a")   # ajout
f = open("fichier.txt", "r+")  # lecture + écriture
f = open("fichier.txt", "rb")  # lecture binaire
f = open("fichier.txt", "wb")  # écriture binaire

12.2 Context manager with

Garantit la fermeture, même en cas d’erreur :

with open("journal.txt", "w", encoding="utf-8") as f:
    f.write("Hello\n")
    f.writelines(["ligne 2\n", "ligne 3\n"])
# f est fermé ici

Lecture :

with open("journal.txt", "r", encoding="utf-8") as f:
    contenu = f.read()          # tout le fichier
    ligne = f.readline()        # une ligne
    lignes = f.readlines()      # liste de lignes

Meilleur pour les gros fichiers :

with open("gros.txt") as f:
    for ligne in f:             # paresseux (buffered)
        traiter(ligne)

12.3 Gestion des chemins : pathlib

API moderne et portable :

from pathlib import Path
 
p = Path("data/sorties")
 
p.exists()              # True/False
p.is_file() / p.is_dir()
p.mkdir(parents=True, exist_ok=True)
p.rename("data/output")
p.unlink()              # supprimer fichier
p.rmdir()               # supprimer dossier vide
p.iterdir()             # contenu du dossier
 
# Écriture/lecture simplifiée
p.write_text("Hello", encoding="utf-8")
contenu = p.read_text(encoding="utf-8")
p.write_bytes(b"binary")
# Chemins
Path("data") / "sub" / "file.txt"
p.suffix                # .txt
p.stem                  # file
p.name                  # file.txt
p.parent                # data/sub

12.4 json

import json
 
data = {"nom": "Alice", "notes": [15, 18, 12]}
 
# Sérialisation
with open("data.json", "w") as f:
    json.dump(data, f, indent=2, ensure_ascii=False)
 
chaine = json.dumps(data, indent=2)
 
# Désérialisation
with open("data.json") as f:
    data = json.load(f)
 
data = json.loads(chaine)

12.5 csv

import csv
 
# Lecture
with open("data.csv", newline="") as f:
    reader = csv.reader(f)
    for ligne in reader:
        print(ligne)  # chaque ligne est une liste
 
# Lecture avec en-têtes
with open("data.csv", newline="") as f:
    reader = csv.DictReader(f)
    for ligne in reader:
        print(ligne["nom"], ligne["âge"])
 
# Écriture
with open("sortie.csv", "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerow(["nom", "âge"])
    writer.writerows([["Alice", 30], ["Bob", 25]])

12.6 Fichiers binaires

with open("image.jpg", "rb") as f:
    data = f.read(1024)  # lire 1024 octets

12.7 io.StringIO / io.BytesIO

Tampons mémoire comme fichiers :

from io import StringIO
 
buf = StringIO()
buf.write("Hello\n")
contenu = buf.getvalue()
buf.close()

12.8 tempfile

from tempfile import NamedTemporaryFile, TemporaryDirectory
 
with NamedTemporaryFile(suffix=".txt", delete=True) as tmp:
    tmp.write(b"temporaire")
    print(tmp.name)
 
with TemporaryDirectory() as tmpdir:
    p = Path(tmpdir) / "test.txt"
    p.write_text("temporaire")

🔗 ← Retour au cours · ← précédent · Suivant →