#!/usr/bin/env python # coding: utf-8 # # Les fichiers # - Il est recommandé d'utiliser les fichiers avec l'instruction **with** pour éviter les problèmes de fermetures. # - On obtient un itérateur ne servant donc qu'une fois. # - L'itérateur renvoie des lignes. Elles se terminent par "\n". # - "ligne.strip()" permet d'enlever les "\n". # - Il y a plusieurs modes d'accès : # * "r" : lecture # * "w" : écriture # * "a" : ajout # # ## I) Lecture dans un fichier # In[14]: # pasteur étant un itérateur, il ne fonctionne qu'une seule fois with open("Fichiers/pasteur.txt","r",encoding="utf-8") as pasteur : for ligne in pasteur : print(repr(ligne)) #pour mieux comprendre le code print("-----------------------------") with open("Fichiers/pasteur.txt","r",encoding="utf-8") as pasteur : # il faut remettre cette ligne !! for ligne in pasteur : print(ligne) # In[23]: # création d'un dictionnaire à partir d'un fichier with open("Fichiers/contact.csv","r",encoding="utf-8") as contact : for ligne in contact : print(ligne) print("---------------------------\n") with open("Fichiers/contact.csv","r",encoding="utf-8") as contact : dico=dict() for ligne in contact : ligne=ligne.strip() # on enlève les fin de ligne "\n" L=ligne.split(" : ") (c,v)=tuple(L) dico[c]=v print(dico) # ## II) Écriture dans un fichier # In[30]: with open("Fichiers/carres.txt","w",encoding="utf-8") as carres : for k in range(100) : carres.write(f"x = {k:2d} ---> x^2 = {k**2:4d}\n") # In[ ]: # In[ ]: # In[ ]: