python--获取当前文件绝对路径的几种方式对比

背景

  1. 在自动化测试中(uiinterface),常需要用到绝对路径,以此增强脚本的健壮性
  2. python内置os模块提供了三种获取当前目录绝对路径的方式,现在来比较一下

获取当前文件的路径

  1. os.getcwd()
  2. os.path.abspath(__file__)
  3. os.path.realpath(__file__)

os.getcwd()

  • 返回「当前工作路径」
  • 工作路径是脚本运行/调用/执行的地方,而「不是脚本本身的地方」
  • 「当前文件路径」跟「当前工作路径」没关系
  • 即获取文件绝对路径时,此方式不可用
  • 源码如下:
def getcwd(*args, **kwargs): # real signature unknown
    """ Return a unicode string representing the current working directory. """
    pass

os.path.abspath(__file__)

  • 返回当前文件的绝对路径
  • 存在软连接时,返回软连接文件路径
  • 源码如下:
    def abspath(path):
        """Return the absolute version of a path."""
        try:
            return normpath(_getfullpathname(path))
        except (OSError, ValueError):
            return _abspath_fallback(path)

os.path.realpath(__file__)

-- 返回当前文件的标准路径,而非软链接所在的路径

总结

  1. 强烈推荐使用 os.path.realpath(\_\_file\_\_)
  2. 利用 os.path.split() 将路径与文件名分离,再通过项目路径与其他路径拼接的方式,获得其他目录的绝对路径
dir_path = os.path.split(os.path.realpath(__file__))[0]
原文地址:https://www.cnblogs.com/xiaohuboke/p/13611234.html