前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >[项目实践] python文件路径引用的

[项目实践] python文件路径引用的

作者头像
py3study
发布2020-01-20 12:04:52
2K0
发布2020-01-20 12:04:52
举报
文章被收录于专栏:python3python3

下面是一个获取配置的代码

代码语言:javascript
复制
 1     def getValue(self,section,option):
 2         """
 3         @file: string,the name of the config file
 4         @section: string,the name of the section in config file
 5         @option: string,the name of the option in section field
 6         This function will return a int value which the option is specified.
 7         """
 8         try:
 9             configs = ConfigParser()
10              filepath = sys.path[1] + "\\config\\" + self.filename + ".ini" 
11 #             print (filepath)
12             line = configs.read(filepath)
13             result = configs.getint(section, option)
14             return int(result)
15         except Exception as e:
16             print (e)

在实际引用该段代码时,随着在其它模块中进行引用时,经常会发现提示模块不存在,为防止后面再出现该问题,将 filepath 这个进行优化,不采用 sys.path方法,改为如下:

代码语言:javascript
复制
 1     def getValue(self,section,option):
 2         """
 3         @file: string,the name of the config file
 4         @section: string,the name of the section in config file
 5         @option: string,the name of the option in section field
 6         This function will return a int value which the option is specified.
 7         """
 8         try:
 9             configs = ConfigParser()
10             filepath = "../config/" + self.filename + ".ini"
11 #             print (filepath)
12             line = configs.read(filepath)
13             result = configs.getint(section, option)
14             return int(result)
15         except Exception as e:
16             print (e)

 从上面代码中看到filepath中加了 ../ 就OK了,那么问题来了 :"../" 代表的是上一级目录, "./"代表的是当前目录,那在实际应用场景中我要如何选用该场景。以下实例将为你一一解开:

先给出目录结构:

1、比如我要执行的文件是common.py文件,那这个时候common.py文件是在二级目录里面(performance/common),如果在common.py文件里面要调用 config文件夹下面的getConfig.py去获取配置信息信息,那么common.py就相当于要先跳出当前common目录到前一级performance目录,然后再去找config目录,这样有返回到前一级目录去找其它目录就要用 "../"

2、假如我把common.py文件移动到performance目录下,这个时候执行common.py文件时,它要去调用config文件夹下面的getConfig.py获取配置信息时,由于这个时候 common.py与config 文件夹属于同级(同属于performance目录),去调用同级目录下的文件时自然可以顺利找到,所以就要用 "./"。

简单一句话概括:以要执行的 a.py文件为参考点,如果所要调用的b.py所在文件夹跟 a.py不在同一级目录,则采用 "../",如果在同一级目录,则采用 "./"

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-03-31 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档