温馨提示×

利用Python的path函数处理相对路径和绝对路径

小樊
154
2024-08-23 11:01:30
栏目: 编程语言
Python开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在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中处理相对路径和绝对路径。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:如何使用dirname函数处理相对路径和绝对路径

0