Verificar con pathlib.Path
En este paso, exploraremos el módulo pathlib, que proporciona una forma orientada a objetos de interactuar con archivos y directorios. Nos centraremos específicamente en utilizar pathlib.Path para verificar la existencia de archivos y directorios, ofreciendo una alternativa a os.path.exists().
El módulo pathlib ofrece un enfoque más moderno e intuitivo para la manipulación de rutas de archivos en comparación con el más antiguo módulo os.path. Representa las rutas de archivos como objetos, lo que te permite realizar diversas operaciones utilizando métodos de esos objetos.
Modifiquemos el script file_paths.py con el que hemos estado trabajando para utilizar pathlib.Path. Abre el archivo file_paths.py en tu editor de VS Code y agrega el siguiente código:
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).")
En este script:
- Importamos la clase
Path del módulo pathlib.
- Creamos objetos
Path tanto para la ruta relativa como para la absoluta del archivo my_file.txt.
- Utilizamos el método
exists() de los objetos Path para comprobar si el archivo existe.
- También comprobamos la existencia del directorio actual y de un archivo que no existe utilizando
pathlib.
Ahora, ejecutemos el script nuevamente. Abre tu terminal en VS Code y ejecuta el script utilizando el siguiente comando:
python file_paths.py
Deberías ver una salida similar a esta:
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).
Esto demuestra cómo utilizar pathlib.Path como alternativa a os.path.exists() para verificar la existencia de archivos y directorios. El módulo pathlib ofrece una forma más orientada a objetos y, a menudo, más legible de interactuar con rutas de archivos en Python.