os相对路径的妙用(摘抄~)+改进

清安无别事 清安无别事 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区

 
  1.     import os
    
        class StudyOS:
    
            def os_path(self):
    
                os_path = os.path.abspath(__file__)
    
                print(f"1、当前执行文件的路径为:{os_path}")
            
            def os_path_d(self):
    
                os_path = os.path.dirname(os.path.abspath(__file__))
    
                print(f"2、当前执行文件的目录路径为:{os_path}")
    
            def os_path_dd(self):
    
                os_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    
                print(f"3、当前执行文件的目录路径的目录路径为:{os_path}")
        
            def os_path_b(self):
    
                os_path = os.path.basename(__file__)
    
                print(f"4、当前执行文件的名称为:{os_path}")
    
            def os_path_e(self):
    
                os_path = os.path.exists(__file__)
    
                print(f"5、当前执行文件是否存在:{os_path}")
    
        if __name__ == "__main__":
    
            mpath = StudyOS()
    
            mpath.os_path()
    
            mpath.os_path_d()
    
            mpath.os_path_dd()
    
            mpath.os_path_b()
    
            mpath.os_path_e()
    
    
1、当前执行文件的路径为:C:\Users\Administrator\Desktop\test_os_path.py

2、当前执行文件的目录路径为:C:\Users\Administrator\Desktop

3、当前执行文件的目录路径的目录路径为:C:\Users\Administrator

4、当前执行文件的名称为:test_os_path.py

5、当前执行文件是否存在:True

 

当你想便捷调用的时候你可以:举个实例:

yaml文件中的内容:

APP:

    dname: emulator-5554

    apk : com.netease.cloudmusic
import os

class StudyOS:

    Base_Path = os.path.abspath(os.path.dirname(os.path.abspath(__file__)) + '/..')

    Base_readpath = Base_Path + r'\reding.yaml

    def __init__(self):

    '''获取data.yaml所有的数据'''

        self.config = YamlRead(Config.Base_Data).getData

    @property

    def devicename(self):

        return self.config['WEBurl']
    
        reConding = StudyOS()

在所需的py文件中你可以直接导入无需实例化就能使用

from * import reCoding

from selenium import webdriver

webUrl = rcCoding.devicename

fox = webdriver.Firefox()

fox.get(webUrl['testurl'])

fox.quit()

后序是博主个人加的,此类有各种的用处,就看你得脑洞了,比如:保存文件的时候你用这样的相对路径就不需要每次都写绝对路径了,并且发给其他人的时候他们也不需要再次更改路径了。原文链接:https://blog.csdn.net/NoamaNelson/article/details/118637260

...全文

相关推荐

评论
收藏 已收藏
分享
返回顶部
清安无别事
清安无别事 优质创作者: 运维技术领域 优质创作者: 运维技术领域
编程新手村 67,947 成员 3,262 内容