__file__ 和 os.path.abspath(__file__) 和 os.path.dirname(os.path.abspath(__file__))

在用python做接口自动化的过程中,遇到os模块下的路径相关的问题,不知道具体用法,现在整理下来
遇到的例子如下
import os
用法一:
basedir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(file))))
sys.path.append(basedir)
print(basedir)

用法二:
datapath = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(file))), ‘data’)
print(os.path.dirname(os.path.dirname(os.path.abspath(file))))
print(datapath)

想要弄明白这两种用法,需要一步一步来
1.先说print( file) #打印当前执行的.py文件路径
__file__ 和 os.path.abspath(__file__) 和 os.path.dirname(os.path.abspath(__file__))
2.再说 os.path.dirname(file) #取当前执行文件的路径的目录部分
__file__ 和 os.path.abspath(__file__) 和 os.path.dirname(os.path.abspath(__file__))
3.再说 os.path.basename(file):取当前执行文件的文件名部分
__file__ 和 os.path.abspath(__file__) 和 os.path.dirname(os.path.abspath(__file__))
4. print(os.path.abspath(file)) #去当前执行文件的绝对路径
__file__ 和 os.path.abspath(__file__) 和 os.path.dirname(os.path.abspath(__file__))
5. 再接下来是比较受偏爱的组合查询
print(os.path.dirname(os.path.abspath(file))) #取当前绝对路径的目录部分
__file__ 和 os.path.abspath(__file__) 和 os.path.dirname(os.path.abspath(__file__))
6.print(os.path.dirname(os.path.dirname(os.path.abspath(file)))) #再往回取一层
__file__ 和 os.path.abspath(__file__) 和 os.path.dirname(os.path.abspath(__file__))
7.print(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(file))))) #再往回取一层,到这一层为止已经是我的项目的根路径了
__file__ 和 os.path.abspath(__file__) 和 os.path.dirname(os.path.abspath(__file__))
8.接着:我把项目的根路径请一个变量指向它
basedir=os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(file))))
并且加到我的系统的路径里面
sys.path.append(basedir)
__file__ 和 os.path.abspath(__file__) 和 os.path.dirname(os.path.abspath(__file__))
9.最后一个是关于os.path.join(path,**path)
data= os.path.join(basedir,"\data")
这里需要注意的就是,**path不可以带斜杠/幺,是路径名称即可
__file__ 和 os.path.abspath(__file__) 和 os.path.dirname(os.path.abspath(__file__))
__file__ 和 os.path.abspath(__file__) 和 os.path.dirname(os.path.abspath(__file__))
到这里就暂时告一段落了,希望可以帮到你~~