python引用文件的方法_[项目实践] python文件路径引用的
下面是一個獲取配置的代碼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方法,改為如下: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不在同一級目錄,則采用 "../",如果在同一級目錄,則采用 "./"
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的python引用文件的方法_[项目实践] python文件路径引用的的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python nonetype_【已解决
- 下一篇: python列表添加元组_【Python