1. A propos de os.path.isdir()
1.1 Qu'est-ce que os.path.isdir() ?
La fonction os.path.isdir() est une méthode du module os.path en Python qui permet de vérifier si un chemin donné correspond à un répertoire existant dans le système de fichiers.
1.2 Importation du module
|
1 2 3 |
import os # ou spécifiquement from os.path import isdir |
2. Syntaxe et Paramètres
2.1 Syntaxe de base
|
1 |
os.path.isdir(path) |
2.2 Paramètre
path : Chaîne de caractères ou objet bytes représentant le chemin à vérifier. Peut être un chemin absolu ou relatif.
2.3 Valeur de retour
Retourne True si le chemin existe ET est un répertoire, sinon retourne False.
3. Utilisation Pratique et Exemples
3.1 Vérification basique
|
1 2 3 4 5 6 7 8 9 |
import os # Vérification de répertoires existants print(os.path.isdir("/home/utilisateur")) # Retourne True si le dossier existe print(os.path.isdir(".")) # Vérifie le répertoire courant print(os.path.isdir("..")) # Vérifie le répertoire parent # Vérification de chemins inexistants print(os.path.isdir("/chemin/inexistant")) # Retourne False |
3.2 Différence avec os.path.isfile()
|
1 2 3 4 5 6 7 8 9 10 |
import os chemin = "/chemin/vers/dossier" if os.path.isdir(chemin): print(f"{chemin} est un répertoire") elif os.path.isfile(chemin): print(f"{chemin} est un fichier") else: print(f"{chemin} n'existe pas ou n'est ni un fichier ni un répertoire") |
3.3 Vérification avec chemins relatifs
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import os # Chemin relatif repertoire_courant = os.getcwd() print(f"Répertoire courant: {repertoire_courant}") # Vérification avec chemin relatif print("Est-ce un dossier?", os.path.isdir("documents")) # Vérification avec construction de chemin chemin_complet = os.path.join(repertoire_courant, "documents") print(f"Chemin complet: {chemin_complet}") print("Est-ce un dossier?", os.path.isdir(chemin_complet)) |
3.4 Utilisation avec os.listdir()
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import os def lister_repertoires(chemin): """Liste uniquement les répertoires dans un chemin donné""" if not os.path.isdir(chemin): print(f"Erreur: {chemin} n'est pas un répertoire valide") return [] elements = os.listdir(chemin) repertoires = [] for element in elements: chemin_complet = os.path.join(chemin, element) if os.path.isdir(chemin_complet): repertoires.append(element) return repertoires # Exemple d'utilisation repertoires = lister_repertoires(".") print("Répertoires dans le dossier courant:", repertoires) |
4. Bonnes Pratiques et Pièges à Éviter
4.1 Vérifier l'existence avant utilisation
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import os def traiter_repertoire(chemin): """Fonction sécurisée pour traiter un répertoire""" if os.path.isdir(chemin): # Le répertoire existe, on peut l'utiliser print(f"Traitement du répertoire: {chemin}") # ... traitement ... else: print(f"Attention: {chemin} n'est pas un répertoire valide") # Gestion d'erreur ou création du répertoire try: os.makedirs(chemin, exist_ok=True) print(f"Répertoire créé: {chemin}") except Exception as e: print(f"Erreur lors de la création: {e}") # Test traiter_repertoire("./mon_dossier") |
4.2 Gestion des liens symboliques
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import os # Création d'un lien symbolique pour test # os.symlink("/chemin/cible", "lien_symbolique") chemin = "lien_symbolique" print(f"isdir: {os.path.isdir(chemin)}") # Vérifie si c'est un dossier (suit les liens) print(f"islink: {os.path.islink(chemin)}") # Vérifie si c'est un lien symbolique print(f"exists: {os.path.exists(chemin)}") # Vérifie si le chemin existe # Pour vérifier si un lien pointe vers un dossier if os.path.islink(chemin): cible = os.readlink(chemin) print(f"Le lien pointe vers: {cible}") print(f"La cible est un dossier: {os.path.isdir(cible)}") |
5. Alternative Moderne : pathlib
5.1 Utilisation de Path.is_dir() avec pathlib
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
from pathlib import Path # Création d'un objet Path chemin = Path("/chemin/vers/dossier") # Vérification avec pathlib if chemin.is_dir(): print(f"{chemin} est un répertoire (vérification avec pathlib)") # Avantages de pathlib print(f"Nom: {chemin.name}") print(f"Parent: {chemin.parent}") print(f"Suffixe: {chemin.suffix}") # Parcourir les sous-dossiers for sous_dossier in chemin.iterdir(): if sous_dossier.is_dir(): print(f" Sous-dossier: {sous_dossier.name}") |
5.2 Comparaison os.path vs pathlib
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import os from pathlib import Path chemin_str = "./mon_dossier" chemin_path = Path(chemin_str) # Avec os.path if os.path.isdir(chemin_str): print("os.path.isdir(): C'est un répertoire") fichiers = [f for f in os.listdir(chemin_str) if os.path.isfile(os.path.join(chemin_str, f))] # Avec pathlib if chemin_path.is_dir(): print("Path.is_dir(): C'est un répertoire") fichiers = [f for f in chemin_path.iterdir() if f.is_file()] # Avantage de pathlib: syntaxe plus propre chemin_complexe = Path(".") / "data" / "2024" / "janvier" if chemin_complexe.is_dir(): print(f"Répertoire trouvé: {chemin_complexe}") |
5.3 Fonction utilitaire complète
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
import os from pathlib import Path def verifier_et_lister_repertoire(chemin): """ Vérifie si un chemin est un répertoire et liste son contenu Compatible avec os.path et pathlib """ # Conversion en Path si c'est une chaîne if isinstance(chemin, str): chemin_obj = Path(chemin) else: chemin_obj = chemin # Vérification if not chemin_obj.is_dir(): return f"Erreur: {chemin_obj} n'est pas un répertoire valide" # Collecte des informations resultat = { 'chemin': str(chemin_obj.absolute()), 'nom': chemin_obj.name, 'existe': chemin_obj.exists(), 'est_repertoire': chemin_obj.is_dir(), 'contenu': [] } # Liste le contenu try: for element in chemin_obj.iterdir(): info = { 'nom': element.name, 'est_fichier': element.is_file(), 'est_repertoire': element.is_dir(), 'taille': element.stat().st_size if element.is_file() else 0 } resultat['contenu'].append(info) except PermissionError: resultat['erreur'] = "Permission refusée" return resultat # Test de la fonction resultat = verifier_et_lister_repertoire(".") print("Résultat de la vérification:") for cle, valeur in resultat.items(): if cle != 'contenu': print(f"{cle}: {valeur}") |
Younes Derfoufi
CRMEF OUJDA



