在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 os
import 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)
请根据你的需求选择合适的方法来获取相对路径