Adloun

Python (école d'ingénieur) · Chapitre 7 · Exercice

Module avec gestion de fichiers

Fichiers, exceptions et modules

Énoncé

Créer un module gestion_contacts.py permettant de gérer un carnet d'adresses stocké au format CSV. Le module doit proposer les fonctions :

  • ajouter_contact(nom, telephone, email)
  • afficher_contacts()
  • rechercher_contact(nom)
  • supprimer_contact(nom)

Corrigé

Dans le fichier gestion_contacts.py :

"""Module de gestion d'un carnet de contacts au format CSV."""
import csv
import os

FICHIER_CONTACTS = "contacts.csv"

def _initialiser_fichier():
    """Crée le fichier avec les en-têtes s'il n'existe pas."""
    if not os.path.exists(FICHIER_CONTACTS):
        with open(FICHIER_CONTACTS, 'w', newline='', encoding='utf-8') as f:
            writer = csv.writer(f)
            writer.writerow(["Nom", "Téléphone", "Email"])

def ajouter_contact(nom, telephone, email):
    """Ajoute un nouveau contact au carnet."""
    _initialiser_fichier()
    with open(FICHIER_CONTACTS, 'a', newline='', encoding='utf-8') as f:
        writer = csv.writer(f)
        writer.writerow([nom, telephone, email])
    print(f"Contact {nom} ajouté.")

def afficher_contacts():
    """Affiche tous les contacts."""
    _initialiser_fichier()
    with open(FICHIER_CONTACTS, 'r', encoding='utf-8') as f:
        reader = csv.reader(f)
        en_tetes = next(reader)
        print(f"{en_tetes[0]:15} {en_tetes[1]:15} {en_tetes[2]:25}")
        print("-" * 55)
        for nom, tel, email in reader:
            print(f"{nom:15} {tel:15} {email:25}")

def rechercher_contact(nom):
    """Recherche un contact par nom. Retourne le contact ou None."""
    _initialiser_fichier()
    with open(FICHIER_CONTACTS, 'r', encoding='utf-8') as f:
        reader = csv.reader(f)
        next(reader)  # Ignorer les en-têtes
        for contact in reader:
            if contact[0].lower() == nom.lower():
                return {"nom": contact[0], "telephone": contact[1], "email": contact[2]}
    return None

def supprimer_contact(nom):
    """Supprime un contact du carnet."""
    _initialiser_fichier()
    contacts = []
    trouve = False
    
    with open(FICHIER_CONTACTS, 'r', encoding='utf-8') as f:
        reader = csv.reader(f)
        en_tetes = next(reader)
        for contact in reader:
            if contact[0].lower() != nom.lower():
                contacts.append(contact)
            else:
                trouve = True
                
    if trouve:
        with open(FICHIER_CONTACTS, 'w', newline='', encoding='utf-8') as f:
            writer = csv.writer(f)
            writer.writerow(en_tetes)
            writer.writerows(contacts)
        print(f"Contact {nom} supprimé.")
    else:
        print(f"Contact {nom} non trouvé.")

if __name__ == "__main__":
    # Tests du module
    ajouter_contact("Alice", "01 23 45 67 89", "alice@email.com")
    ajouter_contact("Bob", "06 98 76 54 32", "bob@email.com")
    afficher_contacts()
    
    print("\nRecherche :", rechercher_contact("Alice"))
    
    supprimer_contact("Bob")
    afficher_contacts()

100 % gratuit

La suite du chapitre est sur Adloun

Exercice suivant et tuteur

Sans compte : le cours et le premier QCM. Exercices et tuteur : inscription gratuite en 30 secondes, sans carte bancaire.

Le cours du chapitre · Tous les exercices du chapitre

Exercice suivant et tuteur →