介绍
在这个实验中,你将学习如何使用不同的方法在 Python 中检查文件是否存在。实验首先会介绍文件路径,解释绝对路径和相对路径之间的区别。你将创建一个示例文本文件和一个 Python 脚本,以演示如何获取当前工作目录,并定义文件的相对路径和绝对路径。
然后,实验将指导你使用 os.path.exists() 函数和 pathlib.Path 对象来验证文件是否存在。这些方法提供了可靠的方式,可在尝试读取或写入文件之前确定文件是否存在,从而避免 Python 程序中可能出现的错误。
在这个实验中,你将学习如何使用不同的方法在 Python 中检查文件是否存在。实验首先会介绍文件路径,解释绝对路径和相对路径之间的区别。你将创建一个示例文本文件和一个 Python 脚本,以演示如何获取当前工作目录,并定义文件的相对路径和绝对路径。
然后,实验将指导你使用 os.path.exists() 函数和 pathlib.Path 对象来验证文件是否存在。这些方法提供了可靠的方式,可在尝试读取或写入文件之前确定文件是否存在,从而避免 Python 程序中可能出现的错误。
在这一步中,我们将探讨 Python 中文件路径的概念。理解文件路径对于读取和写入文件,以及在 Python 程序中导航文件系统至关重要。
文件路径本质上是计算机上文件或目录的地址。主要有两种类型的文件路径:
/home/labex/project/my_file.txt。/home/labex/project,那么相对路径 my_file.txt 所指的文件与绝对路径 /home/labex/project/my_file.txt 相同。让我们首先使用 VS Code 编辑器在 ~/project 目录中创建一个简单的文本文件。创建一个名为 my_file.txt 的新文件,并添加以下内容:
Hello, LabEx!
This is a test file.
将文件保存到 ~/project 目录中。
现在,让我们创建一个 Python 脚本来与这个文件进行交互。在同一个 ~/project 目录中创建一个名为 file_paths.py 的新文件,并添加以下代码:
import os
## Get the current working directory
current_directory = os.getcwd()
print("Current working directory:", current_directory)
## Define a relative path to the file
relative_path = "my_file.txt"
print("Relative path:", relative_path)
## Define an absolute path to the file
absolute_path = os.path.join(current_directory, relative_path)
print("Absolute path:", absolute_path)
在这个脚本中:
os 模块,它提供了与操作系统交互的函数。os.getcwd() 来获取当前工作目录。my_file.txt 文件的相对路径。os.path.join() 来将当前工作目录和相对路径组合成一个绝对路径。现在,让我们运行这个脚本。在 VS Code 中打开终端,并导航到 ~/project 目录(默认情况下你应该已经在该目录中)。然后,使用以下命令执行脚本:
python file_paths.py
你应该会看到类似于以下的输出:
Current working directory: /home/labex/project
Relative path: my_file.txt
Absolute path: /home/labex/project/my_file.txt
这展示了如何在 Python 中获取当前工作目录,并构建相对和绝对文件路径。理解这些概念是在 Python 程序中处理文件和目录的基础。
在这一步中,你将学习如何使用 os.path.exists() 函数来检查文件或目录是否存在。在处理文件时,这是一项基本操作,因为它能让你处理文件可能缺失或目录可能不存在的情况。
os.path.exists() 函数接受一个参数:你要检查的文件或目录的路径。如果文件或目录存在,它返回 True;否则返回 False。
让我们修改上一步创建的 file_paths.py 脚本,以使用 os.path.exists()。在 VS Code 编辑器中打开 file_paths.py 文件,并添加以下代码:
import os
## 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)
## Check if the file exists using the relative path
if os.path.exists(relative_path):
print("The relative path 'my_file.txt' exists.")
else:
print("The relative path 'my_file.txt' does not exist.")
## Check if the file exists using the absolute path
if os.path.exists(absolute_path):
print("The absolute path", absolute_path, "exists.")
else:
print("The absolute path", absolute_path, "does not exist.")
## Check if a directory exists
directory_path = current_directory
if os.path.exists(directory_path):
print("The directory", directory_path, "exists.")
else:
print("The directory", directory_path, "does not exist.")
## Check if a non-existent file exists
non_existent_file = "non_existent_file.txt"
if os.path.exists(non_existent_file):
print("The file", non_existent_file, "exists.")
else:
print("The file", non_existent_file, "does not exist.")
在这个脚本中:
os.path.exists() 来检查 my_file.txt 文件是否存在,同时使用相对路径和绝对路径。False。现在,让我们再次运行这个脚本。在 VS Code 中打开终端,并使用以下命令执行脚本:
python file_paths.py
你应该会看到类似于以下的输出:
The relative path 'my_file.txt' exists.
The absolute path /home/labex/project/my_file.txt exists.
The directory /home/labex/project exists.
The file non_existent_file.txt does not exist.
这展示了如何在 Python 程序中使用 os.path.exists() 来验证文件和目录的存在性。在尝试读取或写入文件之前,这是至关重要的一步,因为它可以避免错误,并确保程序按预期运行。
在这一步中,我们将探索 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 中处理文件路径。
在本次实验中,我们首先探讨了 Python 中文件路径的概念,区分了绝对路径和相对路径。我们了解到,绝对路径提供了文件的完整位置,而相对路径则指定了相对于当前工作目录的位置。
接着,我们创建了一个名为 my_file.txt 的文本文件和一个 Python 脚本 file_paths.py,以演示如何使用 os.getcwd() 获取当前工作目录,以及如何使用 os 模块为创建的文件定义相对路径和绝对路径。