在Python中,获取相对路径可以通过以下方法:
1. 使用 `os.path.relpath` 函数:
import os获取当前文件的绝对路径current_path = os.path.abspath(__file__)获取目标文件的绝对路径target_path = '/path/to/target/file'获取相对路径relative_path = os.path.relpath(target_path, os.path.dirname(current_path))print(relative_path)
2. 使用字符串替换方法:

import os获取当前文件的绝对路径current_path = os.path.abspath(__file__)获取目标文件的绝对路径target_path = '/path/to/target/file'获取当前文件的目录路径current_dir = os.path.dirname(current_path)使用字符串替换获取相对路径relative_path = target_path.replace(current_dir, '.', 1)print(relative_path)
3. 使用正则表达式方法:
import osimport re获取当前文件的绝对路径current_path = os.path.abspath(__file__)获取目标文件的绝对路径target_path = '/path/to/target/file'获取当前文件的目录路径current_dir = os.path.dirname(current_path)使用正则表达式获取相对路径relative_path = re.sub(repr(current_dir).strip("'").strip('"'), '.', repr(target_path).strip("'").strip('"'))print(relative_path)
请根据你的需求选择合适的方法来获取相对路径
