Python os.path.relpath() 方法详解

  • Post category:Python

Python os.path.relpath() 函数

os.path.relpath() 函数返回指定路径到当前工作目录或另一个指定路径的相对路径。

语法

下面是 os.path.relpath() 函数的语法:

os.path.relpath(path[, start])

参数

  • path: 必需,表示一个文件或者目录的路径。
  • start: 可选,表示用来计算相对路径的开始位置。

返回值

返回文件或目录路径的相对路径。 若 start 参数没有被指定,则使用当前工作目录。

使用示例

接下来给大家展示一些使用 os.path.relpath() 函数的示例:

实例 1:

import os

path = "/Users/jack/Documents/projects/website/index.html"
start = "/Users/jack/Documents"

rel_path = os.path.relpath(path, start)
print(rel_path)

输出结果:

projects/website/index.html

实例 2:

import os

path = "/Users/jack/Documents/projects/website/index.html"

rel_path = os.path.relpath(path)
print(rel_path)

输出结果:

../../../Users/jack/Documents/projects/website/index.html

注意

  • start 和 path 的类型都必须是字符串。
  • 如果 start 参数被省略,那么相对路径将被计算到当前目录。
  • 返回的相对路径中,只有斜杠 / 是确定的,在 Windows 下可能会出现不同的情况。

总结

os.path.relpath() 函数是非常实用的函数之一,尤其是在处理文件路径时。我们可以使用这个函数返回指定路径到当前工作目录或者另一个指定路径的相对路径。

关于 os.path.relpath() 函数的详细介绍到这里就结束了,希望大家掌握了这个函数的使用方法。