温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

使用Python怎么获取项目的根路径

发布时间:2021-03-11 17:18:37 来源:亿速云 阅读:971 作者:Leah 栏目:开发技术

本篇文章给大家分享的是有关使用Python怎么获取项目的根路径,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

工具类代码如下:

import sys import os class pathutil(object):   """路径处理工具类"""   def __init__(self):     # 判断调试模式     debug_vars = dict((a, b) for a, b in os.environ.items()              if a.find('IPYTHONENABLE') >= 0)     # 根据不同场景获取根目录     if len(debug_vars) > 0:       """当前为debug运行时"""       self.rootPath = sys.path[2]     elif getattr(sys, 'frozen', False):       """当前为exe运行时"""       self.rootPath = os.getcwd()     else:       """正常执行"""       self.rootPath = sys.path[1]     # 替换斜杠     self.rootPath = self.rootPath.replace("\\", "/")   def getPathFromResources(self, fileName):     """按照文件名拼接资源文件路径"""     filePath = "%s/resources/%s" % (self.rootPath, fileName)     return filePath PathUtil = pathutil() if __name__ == '__main__':   """测试"""   # path = PathUtil.getPathFromResources("context.ini")   print(PathUtil.rootPath)

知识点扩展:Python获取当前目录和上级目录

获取当前文件的路径:

import os print '***获取当前目录***' print os.getcwd() print os.path.abspath(os.path.dirname(__file__)) # __file__ 为当前文件, 若果在ide中运行此行会报错,可改为 #d = path.dirname('.')  # 但是改为.后,就是获得当前目录,接着使用dirname函数访问上级目录 print '***获取上级目录***' print os.path.abspath(os.path.dirname(os.path.dirname(__file__))) print os.path.abspath(os.path.dirname(os.getcwd())) print os.path.abspath(os.path.join(os.getcwd(), "..")) print '***获取上上级目录***' print os.path.abspath(os.path.join(os.getcwd(), "../.."))

以上就是使用Python怎么获取项目的根路径,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI