日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

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

發布時間:2025/4/16 python 16 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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文件路径引用的的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。