configparser讀取配置文件時的相對路徑問題


學習接口測試時,當我把配置文件xx.config和讀取配置文件的模塊read_config.py放在項目下的同一個包config里時,只需傳入文件名xx.config即可實現對配置文件的讀取. 但是當我在項目下另一個包里導入read_config.py后,再次傳入要讀取的配置文件名xx.config,卻報錯了!

Traceback (most recent call last): File "C:\Users\wangyi\AppData\Local\Programs\Python\Python36\lib\configparser.py", line 1138, in _unify_values sectiondict = self._sections[section] KeyError: 'MOD' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:/develop/lemon/tool/read_excel.py", line 88, in <module> button = ReadConfig().read_config('case.config','MOD','button') File "C:\develop\lemon\config\read_config.py", line 18, in read_config return cf.get(section,option) File "C:\Users\wangyi\AppData\Local\Programs\Python\Python36\lib\configparser.py", line 781, in get d = self._unify_values(section, vars) File "C:\Users\wangyi\AppData\Local\Programs\Python\Python36\lib\configparser.py", line 1141, in _unify_values raise NoSectionError(section) configparser.NoSectionError: No section: 'MOD'

糾結了半天,始終找不出錯誤原因,想去百度一下,但是心想這么簡單的問題難道我都解決不了還要去百度?那豈不是太沒面子了呀! 我打開酷狗,放一首古琴曲, 試着讓自己靜下來,但窗外馬路上的汽車鳴笛聲讓我靜不下來,  突然發現, 會不會是路徑有問題?

read_config部分如下:

class ReadConfig: def read_config(self,file_name,section,option): cf = configparser.ConfigParser() cf.read(file_name,encoding='utf-8') return cf.get(section,option) if __name__ == '__main__': r = ReadConfig().read_config('case.config','MOD','button') print(r)

將尋找配置文件的路徑改了一下,加了一行, 讓你不管輸入什么配置文件名都去config包里面去找:

class ReadConfig: def read_config(self,file_name,section,option):  file = os.path.abspath(os.path.join(os.getcwd(),'..','config',file_name)) cf = configparser.ConfigParser() cf.read(file,encoding='utf-8') return cf.get(section,option) if __name__ == '__main__': r = ReadConfig().read_config('case.config','MOD','button') print(r)

 

大功告成, 哈

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM