Can't load relative config file using ConfigParser from sub-directory

后端 未结 3 1528
暖寄归人
暖寄归人 2020-12-29 04:04

I have the following directory structure:

my_program/
       foo.py
       __init__.py # empty
       conf/
          config.cfg
          __init__.py 
         


        
3条回答
  •  猫巷女王i
    2020-12-29 04:31

    you can use os package in python for importing an absolute or relative path to the configuration file. Here is a working example with the relative path (we suppose that config.ini in the folder name configuration that is in the subdirectory of your python script folder):

    import configparser
    import os
    
    path_current_directory = os.path.dirname(__file__)
    path_config_file = os.path.join(path_current_directory, 'configuration', config.ini)
    config = configparser.ConfigParser()
    config.read(path_config_file)
    

提交回复
热议问题