获取当前路径和根目录

今天用到了获取当前路径 和 根目录,记录总结下:

1. 获取当前脚本的路径(包含文件名称)-绝对路径 

a. os.path.abspath(__file__))

    print(os.path.abspath(__file__))

b. os.path.realpath(__file__)

   print(os.path.realpath(__file__))

结果:


2. 获取当前脚本所在目录(不包含当前文件名)

a. os.path.split(os.path.abspath(__file__))[0]

   print(os.path.split(os.path.abspath(__file__))[0])

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

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

结果:


3. 获取根目录,我的根目录是F:\Python\pythonexample\SafeUITesting

方法:

获取步骤2的结果,再使用一次 os.path.dirname()向上退一级;再利用 os.path.split()分割取第0个值即可

a. 得到当前目录: pwd = os.path.dirname(os.path.abspath(__file__))

b. 向上退一级目录: pwd1=os.path.dirname(pwd)

c. 分割最后一个\后和前面的目录:os.path.split(pwd1)[0]

结果:



os.path.split()函数
语法:os.path.split('PATH')
参数说明:
PATH指一个文件的全路径作为参数:
如果给出的是一个目录和文件名,则输出路径和文件名
如果给出的是一个目录名,则输出路径和为空文件名

备注:os.path.split() 将文件名和路径分割开(实际上,该函数的分割并不智能,它仅仅是以 "PATH" 中最后一个 '/' 作为分隔符,分隔后,将索引为0的视为目录(路径),将索引为1的视为文件名)


os.path.join()函数(合并目录)
语法:  os.path.join(path1[,path2[,......]])
返回值:将多个路径组合后返回
注:第一个绝对路径之前的参数将被忽略



猜你喜欢

转载自blog.csdn.net/hou_angela/article/details/80319096