with open("test.txt") as f: contenu = f.read() # lit tout le fichier d'un coupwith open("test.txt") as f: for ligne in f: # lire ligne par ligne (economise la memoire) print(ligne.strip()) # .strip() enleve le retour a la ligne finalwith open("resultat.txt", "w") as f: # 'w' = write, ecrase le contenu existant f.write("Premiere ligne\n")with open("resultat.txt", "a") as f: # 'a' = append, ajoute a la fin f.write("Ligne ajoutee\n")import jsondonnees = {"nom": "Alice", "age": 25}with open("data.json", "w") as f: json.dump(donnees, f, indent=4) # indent=4 : fichier lisible (mise en forme)import jsonwith open("data.json") as f: donnees = json.load(f)print(donnees["nom"]) # acces comme un dictionnaire normalimport jsontexte = json.dumps({"a": 1}) # dict -> chaine JSONdonnees = json.loads(texte) # chaine JSON -> dictimport csvwith open("donnees.csv", newline="") as f: lecteur = csv.reader(f, delimiter=",") for ligne in lecteur: print(ligne) # ex: ['Alice', '25']with open("donnees.csv", newline="") as f: lecteur = csv.DictReader(f) for ligne in lecteur: print(ligne["nom"]) # acces par nom de colonneimport csvwith open("export.csv", "w", newline="") as f: ecrivain = csv.writer(f) ecrivain.writerow(["nom", "age"]) # ligne d'en-tete ecrivain.writerow(["Alice", 25])from pathlib import Pathp = Path("dossier/test.txt")p.exists() # True si le fichier/dossier existep.name # 'test.txt'p.suffix # '.txt' (extension)p.parent # 'dossier' (dossier parent)from pathlib import PathPath("nouveau_dossier").mkdir(exist_ok=True) # cree le dossier s'il n'existe pasfor fichier in Path(".").glob("*.txt"): # tous les .txt du dossier courant print(fichier)