Verificar com pathlib.Path
Nesta etapa, exploraremos o módulo pathlib, que fornece uma maneira orientada a objetos de interagir com arquivos e diretórios. Focaremos especificamente no uso de pathlib.Path para verificar a existência de arquivos e diretórios, oferecendo uma alternativa a os.path.exists().
O módulo pathlib oferece uma abordagem mais moderna e intuitiva para a manipulação de caminhos de arquivos em comparação com o módulo os.path mais antigo. Ele representa caminhos de arquivos como objetos, permitindo que você execute várias operações usando métodos desses objetos.
Vamos modificar o script file_paths.py com o qual temos trabalhado para usar pathlib.Path. Abra o arquivo file_paths.py no seu editor VS Code e adicione o seguinte 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).")
Neste script:
- Importamos a classe
Path do módulo pathlib.
- Criamos objetos
Path para os caminhos relativos e absolutos para my_file.txt.
- Usamos o método
exists() dos objetos Path para verificar se o arquivo existe.
- Também verificamos a existência do diretório atual e de um arquivo inexistente usando
pathlib.
Agora, vamos executar o script novamente. Abra seu terminal no VS Code e execute o script usando o seguinte comando:
python file_paths.py
Você deve ver uma saída semelhante 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).
Isso demonstra como usar pathlib.Path como uma alternativa a os.path.exists() para verificar a existência de arquivos e diretórios. O módulo pathlib oferece uma maneira mais orientada a objetos e, muitas vezes, mais legível de interagir com caminhos de arquivos em Python.