import os
chrome_driver_path = r'drivers\chromedriver.exe'
path2 = r'C:\PythonProject\Amazon\drivers\chromedriver.exe'
print(os.path.abspath(chrome_driver_path))
print(os.path.relpath(path2))
运行结果
C:\PythonProject\Amazon\venv\Scripts\python.exe C:/PythonProject/Amazon/get_path.py
C:\PythonProject\Amazon\drivers\chromedriver.exe
drivers\chromedriver.exe
Process finished with exit code 0
1.绝对路径转相对路径
print os.path.relpath("d:/MyProj/MyFile.txt")
#..\MyProj\MyFile.txt
是根据当前路径的相对路径
2.相对路径转绝对路径
注意用os.chdir(dir)改变当前比较路径
path = "..\MyProj\MyFile.txt"
print os.path.abspath(path)
#D:\MyProj\MyFile.txt