在Python中,可以使用os.path模块来处理相对路径和绝对路径。以下是如何使用os.path模块来处理路径的示例:
import os# 获取当前工作目录current_dir = os.getcwd()print(f"当前工作目录: {current_dir}")# 构建绝对路径absolute_path = os.path.abspath("example.txt")print(f"绝对路径: {absolute_path}")# 构建相对路径relative_path = os.path.relpath("/path/to/example.txt", current_dir)print(f"相对路径: {relative_path}")# 检查路径是否存在path_exists = os.path.exists("example.txt")print(f"路径是否存在: {path_exists}")# 获取路径的目录和文件名dirname = os.path.dirname(absolute_path)basename = os.path.basename(absolute_path)print(f"目录: {dirname}")print(f"文件名: {basename}")在上面的示例中,我们使用os.path模块中的函数来获取当前工作目录、构建绝对路径、构建相对路径、检查路径是否存在,以及获取路径的目录和文件名。这些函数可以帮助您在Python中处理相对路径和绝对路径。


