[项目实践] python文件路径引用的规则,记一次使用sys.path[0]的问题,及如何区分 ../与 ./的使用场景

时间:2022-01-15 16:48:10

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

     def getValue(self,section,option):
"""
@file: string,the name of the config file
@section: string,the name of the section in config file
@option: string,the name of the option in section field
This function will return a int value which the option is specified.
"""
try:
configs = ConfigParser()
filepath = sys.path[1] + "\\config\\" + self.filename + ".ini"
# print (filepath)
line = configs.read(filepath)
result = configs.getint(section, option)
return int(result)
except Exception as e:
print (e)

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

     def getValue(self,section,option):
"""
@file: string,the name of the config file
@section: string,the name of the section in config file
@option: string,the name of the option in section field
This function will return a int value which the option is specified.
"""
try:
configs = ConfigParser()
filepath = "../config/" + self.filename + ".ini"
# print (filepath)
line = configs.read(filepath)
result = configs.getint(section, option)
return int(result)
except Exception as e:
print (e)

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

先给出目录结构:

[项目实践] python文件路径引用的规则,记一次使用sys.path[0]的问题,及如何区分 ../与 ./的使用场景

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不在同一级目录,则采用 "../",如果在同一级目录,则采用 "./"