os相对路径的妙用(摘抄~)+改进
-
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
相关推荐
Python入门学习之:文件 绝对路径和相对路径
在Python入门学习过程中,理解文件操作中的绝对路径和相对路径是至关重要的概念。当前工作目录在Python中扮演着核心角色,它是所有未从根文件夹起始的文件或路径的起点。通过使用os模块,我们可以轻松
理解Python中的绝对路径和相对路径
()来间接获取相对路径print(os.path.abspath("settings.py"))# 获取settings.py所在目录的绝对路径print(os.path.dirname(os.path.abspath
Python 解决相对路径问题:"No such file or directory"
```python import os def read_config(): current_dir = os.path.dirname(os.path.abspath(__file__)) with
详解在Python中以绝对路径或者相对路径导入文件的方法
理解相对路径和绝对路径的区别,并熟悉os模块和sys.path的使用,对解决模块导入问题和提高代码的灵活性和可移植性有着重要意义。在实际应用中,开发者应该根据项目需求和环境来选择最适合的导入方法。
如何表示python中的相对路径
"本文主要介绍了Python中如何表示相对路径,并结合示例解释了相对路径与绝对路径的区别。在Windows环境下,Python中打开文件时经常使用不同的路径表达方式,包括相对路径和绝对路径。同时,文


