使用 pathlib.Path
进行验证
在这一步中,我们将探索 pathlib
模块,它提供了一种面向对象的方式来与文件和目录进行交互。我们将特别关注使用 pathlib.Path
来验证文件和目录的存在性,以此作为 os.path.exists()
的替代方法。
与较旧的 os.path
模块相比,pathlib
模块为文件路径操作提供了更现代、更直观的方法。它将文件路径表示为对象,允许你使用这些对象的方法执行各种操作。
让我们修改之前一直在使用的 file_paths.py
脚本,以使用 pathlib.Path
。在 VS Code 编辑器中打开 file_paths.py
文件,并添加以下代码:
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).")
在这个脚本中:
- 我们从
pathlib
模块导入 Path
类。
- 我们为
my_file.txt
的相对路径和绝对路径创建 Path
对象。
- 我们使用
Path
对象的 exists()
方法来检查文件是否存在。
- 我们还使用
pathlib
检查当前目录和一个不存在的文件是否存在。
现在,让我们再次运行这个脚本。在 VS Code 中打开终端,并使用以下命令执行脚本:
python file_paths.py
你应该会看到类似于以下的输出:
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).
这展示了如何使用 pathlib.Path
作为 os.path.exists()
的替代方法来验证文件和目录的存在性。pathlib
模块提供了一种更面向对象且通常更易读的方式来在 Python 中处理文件路径。