0% ont trouvé ce document utile (0 vote)
11 vues10 pages

Guide du module pathlib en Python

Le document est un guide complet sur le module pathlib de Python, qui permet de manipuler des chemins de fichiers de manière orientée objet. Il couvre les classes principales, les méthodes fondamentales, ainsi que des opérations sur les fichiers et répertoires, tout en fournissant des exemples pratiques et des conseils de bonnes pratiques. La conclusion met en avant les avantages du module et propose des pistes pour approfondir le sujet.

Transféré par

claive295
Copyright
© All Rights Reserved
Nous prenons très au sérieux les droits relatifs au contenu. Si vous pensez qu’il s’agit de votre contenu, signalez une atteinte au droit d’auteur ici.
Formats disponibles
Téléchargez aux formats PDF, TXT ou lisez en ligne sur Scribd
0% ont trouvé ce document utile (0 vote)
11 vues10 pages

Guide du module pathlib en Python

Le document est un guide complet sur le module pathlib de Python, qui permet de manipuler des chemins de fichiers de manière orientée objet. Il couvre les classes principales, les méthodes fondamentales, ainsi que des opérations sur les fichiers et répertoires, tout en fournissant des exemples pratiques et des conseils de bonnes pratiques. La conclusion met en avant les avantages du module et propose des pistes pour approfondir le sujet.

Transféré par

claive295
Copyright
© All Rights Reserved
Nous prenons très au sérieux les droits relatifs au contenu. Si vous pensez qu’il s’agit de votre contenu, signalez une atteinte au droit d’auteur ici.
Formats disponibles
Téléchargez aux formats PDF, TXT ou lisez en ligne sur Scribd

Guide complet du module pathlib de Python

NKOKOLO MALANDA CLAIVE


November 7, 2025

Contents
1 Introduction 1

2 Classes principales 2
2.1 Vue d’ensemble des classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
2.2 Création d’objets Path . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2

3 Méthodes fondamentales 2
3.1 Manipulation des composants de chemin . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
3.2 Modification de chemins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
3.3 Méthodes de vérification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
3.4 Méthodes de résolution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

4 Manipulation de chemins 3
4.1 Opérations sur les chemins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

5 Opérations sur les fichiers 4


5.1 Création et suppression de fichiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
5.2 Manipulation du contenu des fichiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
5.3 Informations sur les fichiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

6 Opérations sur les répertoires 5


6.1 Création et suppression de répertoires . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
6.2 Exploration de répertoires . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
6.3 Manipulation avancée de répertoires . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
6.4 Exemple pratique: organisation de fichiers . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

7 Exemple complet: Gestionnaire de projet 6

8 Best Practices et Conseils 9


8.1 Recommandations générales . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
8.2 Gestion des erreurs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
8.3 Compatibilité avec l’ancien code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9

9 Conclusion 10
9.1 Avantages principaux . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
9.2 Pour aller plus loin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

1 Introduction
Le module pathlib fournit des classes pour représenter et manipuler des chemins de fichiers de manière
orientée objet. Il offre une alternative moderne aux modules traditionnels comme [Link].

1
2 Classes principales
2.1 Vue d’ensemble des classes
Pathlib propose plusieurs classes hiérarchisées :

- PurePath : Classe de base pour la manipulation de chemins


PurePosixPath : Pour les systèmes de type Unix
PureWindowsPath : Pour les systèmes Windows

- Path : Classe concrète principale (selon le système d’exploitation)


PosixPath : Pour Unix/Linux/MacOS
WindowsPath : Pour Windows

2.2 Création d’objets Path


1 from pathlib import Path
2
3 # D i f f r e n t e s f a o n s de c r e r des chemins
4 chemin_absolu = Path ( " / home / utilisateur / documents " )
5 ch emin_r elatif = Path ( " documents / fichier . txt " )
6 ch emin_c ourant = Path . cwd () # R p e r t o i r e courant
7 chemin_home = Path . home () # R p e r t o i r e home
8
9 # Chemin avec plusieurs parties
10 ch em i n_ co m pl e xe = Path ( " / var " ) / " log " / " apache " / " access . log "

3 Méthodes fondamentales
3.1 Manipulation des composants de chemin
1 chemin = Path ( " / home / user / documents / rapport . pdf " )
2
3 # Composants du chemin
4 print ( f " Nom : { chemin . name } " ) # ’ rapport . pdf ’
5 print ( f " Stem : { chemin . stem } " ) # ’ rapport ’
6 print ( f " Suffixe : { chemin . suffix } " ) # ’. pdf ’
7 print ( f " Suffixes : { chemin . suffixes } " ) # [ ’. pdf ’]
8 print ( f " Parent : { chemin . parent } " ) # ’/ home / user / documents ’
9 print ( f " A n c t r e s : { list ( chemin . parents ) } " )
10 print ( f " Racine : { chemin . root } " ) # ’/ ’
11 print ( f " Parties : { chemin . parts } " ) # ( ’/ ’ , ’ home ’, ’ user ’, ...)
12
13 # Chemin de travail
14 print ( f " Est absolu : { chemin . is_absolute () } " )
15 print ( f " Est relatif : { not chemin . is_absolute () } " )

3.2 Modification de chemins


1 # Joindre des chemins avec l ’ o p r a t e u r /
2 base = Path ( " / home / user " )
3 complet = base / " documents " / " fichier . txt "
4
5 # M t h o d e s de t ransfo rmatio n
6 chemin = Path ( " / home / user / documents / rapport . pdf " )
7
8 # Changer le nom
9 nouveau_nom = chemin . with_name ( " nouveau . pdf " )
10 print ( nouveau_nom ) # ’/ home / user / documents / nouveau . pdf ’
11
12 # Changer l ’ extension
13 nouvelle_ext = chemin . with_suffix ( " . txt " )
14 print ( nouvelle_ext ) # ’/ home / user / documents / rapport . txt ’
15

2
16 # Changer le stem
17 nouveau_stem = chemin . with_stem ( " compte_rendu " )
18 print ( nouveau_stem ) # ’/ home / user / documents / compte_rendu . pdf ’
19
20 # Expansion du tilde (~)
21 chemin_tilde = Path ( " ~/ documents " ) . expanduser ()

3.3 Méthodes de vérification


1 chemin = Path ( " / home / user / documents / rapport . pdf " )
2
3 # V r i f i c a t i o n s de type
4 print ( f " Existe : { chemin . exists () } " ) # True / False
5 print ( f " Est fichier : { chemin . is_file () } " ) # True si c ’ est un fichier
6 print ( f " Est dossier : { chemin . is_dir () } " ) # True si c ’ est un r p e r t o i r e
7 print ( f " Est absolu : { chemin . is_absolute () } " ) # True si chemin absolu
8 print ( f " Est lien : { chemin . is_symlink () } " ) # True si lien symbolique
9 print ( f " Est socket : { chemin . is_socket () } " ) # True si socket
10 print ( f " Est FIFO : { chemin . is_fifo () } " ) # True si tube n o m m
11 print ( f " Est bloc : { chemin . i s_ b lo c k_ de v ic e () } " ) # True si p r i p h r i q u e bloc
12 print ( f " Est char : { chemin . is_ch ar_dev ice () } " ) # True si p r i p h r i q u e c a r a c t r e

3.4 Méthodes de résolution


1 # R s o l u t i o n de chemins
2 chemin = Path ( " documents /../ fichier . txt " )
3 absolu = chemin . resolve () # Chemin absolu r s o l u
4 print ( f " R s o l u : { absolu } " )
5
6 # Chemin absolu simple
7 absolu_simple = chemin . absolute ()
8
9 # Chemin relatif
10 base = Path ( " / home / user " )
11 relatif = chemin . relative_to ( base )
12 print ( f " Relatif { base }: { relatif } " )
13
14 # V r i f i c a t i o n si un chemin est relatif un autre
15 try :
16 relatif = Path ( " / home / user / documents " ) . relative_to ( " / home " )
17 print ( f " Chemin relatif : { relatif } " ) # ’ user / documents ’
18 except ValueError :
19 print ( " Le chemin n ’ est pas relatif la base " )

4 Manipulation de chemins
4.1 Opérations sur les chemins
1 # C o n c a t n a t i o n avec l ’ o p r a t e u r /
2 chemin1 = Path ( " / home / user " )
3 chemin2 = Path ( " documents " )
4 complet = chemin1 / chemin2
5 print ( f " Chemin complet : { complet } " )
6
7 # Comparaison de chemins
8 print ( f " gaux : { chemin1 == chemin2 } " )
9 print ( f " Dans : { chemin1 in [ chemin1 , chemin2 ]} " )
10
11 # Corre sponda nce de motifs avec glob
12 for fichier in Path ( " . " ) . glob ( " *. txt " ) :
13 print ( f " Fichier texte : { fichier } " )
14
15 # Recherche r c u r s i v e avec rglob
16 for fichier in Path ( " . " ) . rglob ( " *. py " ) :
17 print ( f " Fichier Python : { fichier } " )

3
18
19 # Recherche avec des motifs complexes
20 for fichier in Path ( " . " ) . glob ( " **/*[0 -9]. txt " ) :
21 print ( f " Fichier avec chiffre : { fichier } " )

5 Opérations sur les fichiers


5.1 Création et suppression de fichiers
1 # C r e r un fichier
2 fichier = Path ( " nouveau . txt " )
3 fichier . touch () # C r e le fichier s ’ il n ’ existe pas
4 fichier . touch ( exist_ok = True ) # Ne l v e pas d ’ erreur si existe d j
5
6 # Supprimer un fichier
7 fichier . unlink ()
8 fichier . unlink ( missing_ok = True ) # Python 3.8+: pas d ’ erreur si manquant
9
10 # Renommer / d p l a c e r
11 ancien = Path ( " ancien . txt " )
12 nouveau = Path ( " nouveau . txt " )
13 ancien . rename ( nouveau )
14
15 # Remplacer ( identique rename mais avec gestion d ’ erreurs )
16 ancien . replace ( nouveau )
17
18 # C r a t i o n avec contenu initial
19 fichier . write_text ( " Contenu initial " )

5.2 Manipulation du contenu des fichiers


1 fichier = Path ( " exemple . txt " )
2
3 # crire du texte
4 fichier . write_text ( " Bonjour le monde !\ nCeci est un test . " , encoding = ’ utf -8 ’)
5
6 # Lire du texte
7 contenu = fichier . read_text ( encoding = ’utf -8 ’)
8 print ( contenu )
9
10 # crire des bytes
11 donnees = b " Donn \ xc3 \ xa9es binaires "
12 fichier . write_bytes ( donnees )
13
14 # Lire des bytes
15 donnees_lues = fichier . read_bytes ()
16
17 # Ouvrir avec gestion de contexte
18 with fichier . open ( ’r ’ , encoding = ’utf -8 ’) as f :
19 for ligne in f :
20 print ( ligne . strip () )
21
22 # Ajouter du contenu
23 with fichier . open ( ’a ’ , encoding = ’utf -8 ’) as f :
24 f . write ( " \ nNouvelle ligne a j o u t e " )

5.3 Informations sur les fichiers


1 fichier = Path ( " exemple . txt " )
2
3 # M t a d o n n e s avec stat ()
4 stat = fichier . stat ()
5 print ( f " Taille : { stat . st_size } octets " )
6 print ( f " Date modification : { stat . st_mtime } " )
7 print ( f " Date a c c s : { stat . st_atime } " )

4
8 print ( f " Date c r a t i o n : { stat . st_ctime } " )
9 print ( f " Permissions : { oct ( stat . st_mode ) } " )
10 print ( f " P r o p r i t a i r e : { stat . st_uid } " )
11 print ( f " Groupe : { stat . st_gid } " )
12
13 # M t h o d e s utilitaires pour les permissions
14 import os
15 print ( f " Lisible : { os . access ( fichier , os . R_OK ) } " )
16 print ( f " Modifiable : { os . access ( fichier , os . W_OK ) } " )
17 print ( f " E x c u t a b l e : { os . access ( fichier , os . X_OK ) } " )
18
19 # P r o p r i t a i r e et groupe ( Unix seulement )
20 try :
21 print ( f " P r o p r i t a i r e : { fichier . owner () } " )
22 print ( f " Groupe : { fichier . group () } " )
23 except N o t I m p l e m e n t e d E r r o r :
24 print ( " Non disponible sur ce s y s t m e " )

6 Opérations sur les répertoires


6.1 Création et suppression de répertoires
1 # C r e r un r p e r t o i r e simple
2 dossier = Path ( " no u ve au _ do s si er " )
3 dossier . mkdir () # C r e le dossier
4
5 # C r e r des r p e r t o i r e s parents si n c e s s a i r e
6 do ss i er _ pr of o nd = Path ( " a / b / c / d " )
7 do ss i er _ pr of o nd . mkdir ( parents = True , exist_ok = True )
8
9 # C r e r avec des permissions s p c i f i q u e s ( Unix )
10 dossier . mkdir ( mode =0 o755 , exist_ok = True )
11
12 # Supprimer un r p e r t o i r e ( doit tre vide )
13 dossier . rmdir ()
14
15 # Supprimer un r p e r t o i r e non vide ( n c e s s i t e shutil )
16 import shutil
17 shutil . rmtree ( d os s ie r_ p ro fo n d )
18
19 # C r a t i o n temporaire
20 import tempfile
21 with tempfile . T e m p o r a r y D i r e c t o r y () as tmpdir :
22 tmp_path = Path ( tmpdir )
23 print ( f " R p e r t o i r e temporaire : { tmp_path } " )

6.2 Exploration de répertoires


1 dossier = Path ( " . " )
2
3 # Lister le contenu avec iterdir ()
4 print ( " Contenu du r p e r t o i r e : " )
5 for element in dossier . iterdir () :
6 type_element = " D " if element . is_dir () else " F "
7 print ( f " { type_element } { element . name } " )
8
9 # Recherche avec glob - non r c u r s i f
10 print ( " \ nFichiers Python directs : " )
11 for fichier_py in dossier . glob ( " *. py " ) :
12 print ( f " { fichier_py } " )
13
14 # Recherche r c u r s i v e avec rglob
15 print ( " \ nTous les fichiers Python r c u r s i v e m e n t : " )
16 for fichier_py in dossier . rglob ( " *. py " ) :
17 print ( f " { fichier_py } " )
18
19 # Filtrage a v a n c
20 print ( " \ nFichiers de configuration : " )

5
21 for fichier in dossier . glob ( " *.{ json , yaml , yml , toml } " ) :
22 print ( f " { fichier } " )
23
24 # Tri des r s u l t a t s
25 fichiers_py = sorted ( dossier . glob ( " *. py " ) )

6.3 Manipulation avancée de répertoires


1 # Parcourir la h i r a r c h i e parente
2 chemin = Path ( " / a / b / c / d / e / f . txt " )
3 print ( " H i r a r c h i e parente : " )
4 for parent in chemin . parents :
5 print ( f " { parent } " )
6
7 # Travail avec le r p e r t o i r e courant
8 courant = Path . cwd ()
9 print ( f " R p e r t o i r e courant : { courant } " )
10
11 # Changer de r p e r t o i r e ( n c e s s i t e os )
12 import os
13 os . chdir ( " / nouveau / chemin " )
14
15 # R p e r t o i r e home
16 home = Path . home ()
17 print ( f " R p e r t o i r e home : { home } " )
18
19 # Chemins s p c i a u x
20 print ( f " S p a r a t e u r : { os . path . sep } " )
21 print ( f " Separateur alt : { os . path . altsep } " )

6.4 Exemple pratique: organisation de fichiers


1 def o r g a n i se r _ f i c h i e r s ( dos sier_s ource ) :
2 " " " Organise les fichiers par extension " " "
3 source = Path ( do ssier_ source )
4
5 if not source . exists () :
6 print ( f " Le dossier { source } n ’ existe pas " )
7 return
8
9 for fichier in source . iterdir () :
10 if fichier . is_file () :
11 # Extraire l ’ extension ( sans le point )
12 extension = fichier . suffix [1:] if fichier . suffix else " sans_e xtensi on "
13
14 # C r e r le dossier de destination
15 dossier_dest = source / extension
16 dossier_dest . mkdir ( exist_ok = True )
17
18 # D p l a c e r le fichier
19 destination = dossier_dest / fichier . name
20 fichier . rename ( destination )
21 print ( f " D p l a c : { fichier . name } -> { extension }/ " )
22
23 # Utilisation
24 o r g a n i s e r _ f i c h i e r s ( " ~/ T l c h a r g e m e n t s " )

7 Exemple complet: Gestionnaire de projet


1 from pathlib import Path
2 import datetime
3 import shutil
4
5 class G e s t i o n n a i r e P r o j e t :
6 def __init__ ( self , racine_projet ) :
7 self . racine = Path ( racine_projet ) . expanduser () . resolve ()

6
8 self . structure = {
9 ’ src ’: [ ’ main . py ’ , ’ utils . py ’ , ’ __init__ . py ’] ,
10 ’ tests ’: [ ’ test_main . py ’ , ’ test_utils . py ’ , ’ __init__ . py ’] ,
11 ’ docs ’: [ ’ README . md ’ , ’ requirements . txt ’ , ’ conf . py ’] ,
12 ’ data ’: [ ’ input ’ , ’ output ’] ,
13 ’ logs ’: [] ,
14 ’ config ’: [ ’ settings . json ’ , ’ logging . conf ’]
15 }
16
17 def c re e r_ st r uc tu r e ( self ) :
18 " " " C r e la structure c o m p l t e du projet " " "
19 print ( f " C r a t i o n du projet dans : { self . racine } " )
20
21 # C r e r le r p e r t o i r e racine
22 self . racine . mkdir ( parents = True , exist_ok = True )
23
24 for dossier , elements in self . structure . items () :
25 c hemin_ dossie r = self . racine / dossier
26 c hemin_ dossie r . mkdir ( exist_ok = True )
27 print ( f " Cr : { chemin _dossi er . relative_to ( self . racine ) } " )
28
29 for element in elements :
30 chemi n_elem ent = ch emin_d ossier / element
31 if ’. ’ in element : # C ’ est un fichier
32 # Ajouter un contenu par d f a u t pour les fichiers Python
33 if element . endswith ( ’. py ’) :
34 if element == ’ __init__ . py ’:
35 chem in_ele ment . write_text ( ’# Package i nitial isatio n \ n ’)
36 elif element == ’ main . py ’:
37 chem in_ele ment . write_text ( ’ #!/ usr / bin / env python3 \ n \ nprint ("
Hello World !") \ n ’)
38 else :
39 chem in_ele ment . touch ()
40 else :
41 chemin _eleme nt . touch ()
42 print ( f " Cr : { che min_el ement . relative_to ( self . racine ) } " )
43 else : # C ’ est un sous - dossier
44 ( c hemin_ dossie r / element ) . mkdir ( exist_ok = True )
45 print ( f " Cr : {( ch emin_d ossier / element ) . relative_to (
self . racine ) } " )
46
47 print ( f " \ n Structure cr e avec s u c c s ! " )
48
49 def g en e re r_ r ap po r t ( self ) :
50 " " " G n r e un rapport d t a i l l de la structure du projet " " "
51 rapport = self . racine / " r a p p o r t _ s t r u c t u r e . txt "
52
53 with rapport . open ( ’w ’ , encoding = ’utf -8 ’) as f :
54 f . write ( f " Rapport de structure du projet \ n " )
55 f . write ( f " G n r le : { datetime . datetime . now () }\ n " )
56 f . write ( f " Racine : { self . racine }\ n " )
57 f . write ( " = " * 60 + " \ n \ n " )
58
59 t otal_f ichier s = 0
60 t otal_d ossier s = 0
61
62 for element in sorted ( self . racine . rglob ( ’* ’) ) :
63 relatif = element . relative_to ( self . racine )
64 indent = " " * ( len ( relatif . parts ) - 1)
65
66 if element . is_dir () :
67 type_emoji = " "
68 tot al_dos siers += 1
69 else :
70 type_emoji = " "
71 tot al_fic hiers += 1
72 # Ajouter la taille pour les fichiers
73 taille = element . stat () . st_size
74 f . write ( f " { indent }{ type_emoji } { relatif } ({ taille } octets ) \ n " )
75 f . write ( f " { indent }{ type_emoji } { relatif }\ n " )
76
77 f . write ( f " \ n R s u m :\ n " )
78 f . write ( f " Dossiers : { t otal_d ossier s }\ n " )

7
79 f . write ( f " Fichiers : { t otal_f ichier s }\ n " )
80 f . write ( f " Total : { total_ dossie rs + tot al_fic hiers } lments \n")
81
82 print ( f " Rapport g n r : { rapport } " )
83 return rapport
84
85 def t r o u v e r _ f i c h i e r s ( self , motif ) :
86 " " " Trouve tous les fichiers correspondant au motif " " "
87 print ( f " Recherche de : ’{ motif } ’ " )
88 resultats = list ( self . racine . rglob ( motif ) )
89
90 if not resultats :
91 print ( " Aucun fichier t r o u v " )
92 return
93
94 for fichier in sorted ( resultats ) :
95 if fichier . is_file () :
96 relatif = fichier . relative_to ( self . racine )
97 taille = fichier . stat () . st_size
98 print ( f " { relatif } ({ taille } octets ) " )
99
100 def c a l c u l e r _ t a i l l e _ t o t a l e ( self ) :
101 " " " Calcule la taille totale du projet en octets " " "
102 total = 0
103 fichiers_comptes = 0
104
105 for fichier in self . racine . rglob ( ’* ’) :
106 if fichier . is_file () :
107 total += fichier . stat () . st_size
108 f i c h i e r s _ c o m p t e s += 1
109
110 print ( f " Taille totale : { total } octets " )
111 print ( f " Soit : { total / 1024:.2 f } KB " )
112 print ( f " Soit : { total / 1024 / 1024:.2 f } MB " )
113 print ( f " Fichiers a n a l y s s : { f i c h i e r s _ c o m p t e s } " )
114
115 return total
116
117 def n et t oy er _ pr oj e t ( self ) :
118 " " " Supprime c o m p l t e m e n t le projet " " "
119 if self . racine . exists () :
120 reponse = input ( f " tes - vous s r de vouloir supprimer { self . racine }? ( o / N ) :
")
121 if reponse . lower () == ’o ’:
122 shutil . rmtree ( self . racine )
123 print ( f " Projet s u p p r i m : { self . racine } " )
124 else :
125 print ( " Suppression a n n u l e " )
126 else :
127 print ( " Le projet n ’ existe pas " )
128
129 # Utilisation et d m o n s t r a t i o n
130 if __name__ == " __main__ " :
131 # C r a t i o n du gestionnaire
132 projet = G e s t i o n n a i r e P r o j e t ( " ~/ m o n _ s u p e r _ p r o j e t " )
133
134 # C r a t i o n de la structure
135 projet . cr e er _s t ru ct u re ()
136
137 # G n r a t i o n du rapport
138 projet . ge n er er _ ra pp o rt ()
139
140 # Recherche de fichiers
141 projet . t r o u v e r _ f i c h i e r s ( " *. py " )
142 projet . t r o u v e r _ f i c h i e r s ( " *. md " )
143
144 # Calcul de la taille
145 projet . c a l c u l e r _ t a i l l e _ t o t a l e ()
146
147 # Nettoyage ( d c o m m e n t e r pour tester )
148 # projet . n e tt oy e r_ pr o je t ()

8
8 Best Practices et Conseils
8.1 Recommandations générales
• Toujours utiliser Path pour les chemins au lieu des chaînes de caractères
• Utiliser resolve() pour obtenir des chemins absolus propres
• Préférer l’opérateur / pour joindre des chemins plutôt que [Link]()
• Utiliser exist_ok=True avec mkdir() pour éviter les erreurs
• Utiliser relative_to() pour les chemins relatifs entre deux paths
• Préférer read_text()/write_text() pour les fichiers texte simples

8.2 Gestion des erreurs


1 from pathlib import Path
2
3 def m a n i p u l e r _ c h e m i n _ s e c u r i s e ( chemin ) :
4 " " " Exemple de manipulation s c u r i s e avec gestion d ’ erreurs " " "
5 try :
6 path = Path ( chemin )
7
8 # V r i f i e r l ’ existence
9 if not path . exists () :
10 print ( f " Le chemin { path } n ’ existe pas " )
11 return
12
13 # Op rations s c u r i s e s
14 if path . is_file () :
15 contenu = path . read_text ( encoding = ’utf -8 ’)
16 print ( f " Contenu : { contenu [:100]}... " )
17 elif path . is_dir () :
18 for element in path . iterdir () :
19 print ( f " { element . name } " )
20
21 except Pe r mi s si on E rr or :
22 print ( f " Permission r e f u s e pour { chemin } " )
23 except U n i c o d e D e c o d e E r r o r :
24 print ( f " Erreur de d c o d a g e pour { chemin } " )
25 except Exception as e :
26 print ( f " Erreur inattendue : { e } " )
27
28 # Utilisation
29 m a n i p u l e r _ c h e m i n _ s e c u r i s e ( " / f i c h i e r _ i m p o r t a n t . txt " )

8.3 Compatibilité avec l’ancien code


1 # Conversion depuis os . path
2 import os
3 from pathlib import Path
4
5 chemin_os = " / home / user / documents "
6 ch emin_p athlib = Path ( chemin_os )
7
8 # Conversion inverse
9 ch emin_p athlib = Path ( " / home / user / documents " )
10 chemin_os = str ( c hemin_ pathli b )
11
12 # M thodes quivalentes
13 print ( f " os . path . exists : { os . path . exists ( chemin_os ) } " )
14 print ( f " Path . exists : { chemi n_path lib . exists () } " )
15
16 print ( f " os . path . isdir : { os . path . isdir ( chemin_os ) } " )
17 print ( f " Path . is_dir : { chemi n_path lib . is_dir () } " )
18
19 # Utilisation avec des APIs qui attendent des strings

9
20 with open ( chemin_pathlib , ’r ’) as f : # Conversion automatique
21 contenu = f . read ()

9 Conclusion
Le module pathlib offre une API orientée objet moderne et intuitive pour la manipulation de chemins
de fichiers. Introduit dans Python 3.4 et considéré comme la méthode privilégiée depuis Python 3.6, il
remplace avantageusement les anciens modules [Link] et glob.

9.1 Avantages principaux


• Syntaxe intuitive avec l’opérateur / pour la concaténation

• Approche orientée objet cohérente


• Indépendance du système grâce aux classes spécialisées
• Méthodes riches pour les opérations courantes
• Meilleure lisibilité du code

• Intégration native avec le reste de la bibliothèque standard

9.2 Pour aller plus loin


• Documentation officielle: [Link]
• PEP 428: [Link]
• Référence des méthodes: [Link]

10

Vous aimerez peut-être aussi