欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

绝对路径和相对路径 转换

程序员文章站 2022-05-09 23:12:32
...
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
相关标签: python