• 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]
    
  • 相关阅读:
    关于GIS从业人员的定位
    《企业应用架构模式》读书笔记(4)
    各大网络、软件巨头涉足Web GIS
    流水帐(2005.5)
    Xtreme Suite 和 Toolkit 9.6发布
    一个算法问题
    推荐2个最近使用的软件
    linux之pmap命令
    linux 文件系统简介
    百度脚本笔试题两道
  • 原文地址:https://www.cnblogs.com/xiaohuboke/p/13611234.html
Copyright © 2020-2023  润新知