Vérification avec pathlib.Path
Dans cette étape, nous allons explorer le module pathlib
, qui offre une approche orientée objet pour interagir avec les fichiers et les répertoires. Nous allons nous concentrer plus particulièrement sur l'utilisation de pathlib.Path
pour vérifier l'existence de fichiers et de répertoires, offrant une alternative à os.path.exists()
.
Le module pathlib
propose une approche plus moderne et intuitive pour manipuler les chemins de fichiers par rapport au module plus ancien os.path
. Il représente les chemins de fichiers sous forme d'objets, vous permettant d'effectuer diverses opérations en utilisant les méthodes de ces objets.
Modifions le script file_paths.py
sur lequel nous avons travaillé pour utiliser pathlib.Path
. Ouvrez le fichier file_paths.py
dans votre éditeur VS Code et ajoutez le code suivant :
import os
from pathlib import Path
## Get the current working directory
current_directory = os.getcwd()
## Define a relative path to the file
relative_path = "my_file.txt"
## Define an absolute path to the file
absolute_path = os.path.join(current_directory, relative_path)
## Create Path objects for relative and absolute paths
relative_path_obj = Path(relative_path)
absolute_path_obj = Path(absolute_path)
## Check if the file exists using the relative path object
if relative_path_obj.exists():
print("The relative path 'my_file.txt' exists (using pathlib).")
else:
print("The relative path 'my_file.txt' does not exist (using pathlib).")
## Check if the file exists using the absolute path object
if absolute_path_obj.exists():
print("The absolute path", absolute_path, "exists (using pathlib).")
else:
print("The absolute path", absolute_path, "does not exist (using pathlib).")
## Check if a directory exists using pathlib
directory_path_obj = Path(current_directory)
if directory_path_obj.exists():
print("The directory", current_directory, "exists (using pathlib).")
else:
print("The directory", current_directory, "does not exist (using pathlib).")
## Check if a non-existent file exists using pathlib
non_existent_file = "non_existent_file.txt"
non_existent_path_obj = Path(non_existent_file)
if non_existent_path_obj.exists():
print("The file", non_existent_file, "exists (using pathlib).")
else:
print("The file", non_existent_file, "does not exist (using pathlib).")
Dans ce script :
- Nous importons la classe
Path
du module pathlib
.
- Nous créons des objets
Path
pour le chemin relatif et le chemin absolu du fichier my_file.txt
.
- Nous utilisons la méthode
exists()
des objets Path
pour vérifier si le fichier existe.
- Nous vérifions également l'existence du répertoire actuel et d'un fichier inexistant en utilisant
pathlib
.
Maintenant, exécutons à nouveau le script. Ouvrez votre terminal dans VS Code et exécutez le script en utilisant la commande suivante :
python file_paths.py
Vous devriez voir une sortie similaire à ceci :
The relative path 'my_file.txt' exists (using pathlib).
The absolute path /home/labex/project/my_file.txt exists (using pathlib).
The directory /home/labex/project exists (using pathlib).
The file non_existent_file.txt does not exist (using pathlib).
Cela démontre comment utiliser pathlib.Path
comme alternative à os.path.exists()
pour vérifier l'existence de fichiers et de répertoires. Le module pathlib
offre une approche plus orientée objet et souvent plus lisible pour interagir avec les chemins de fichiers en Python.