在读取“ .ini”文件时获取“ KeyError”

时间:2019-02-23 12:45:31

标签: python pycharm

我在PyCharm中有一个python项目,我具有以下目录结构:

MyProject
 |_d1
   |_d2
     |_d3
      |_Main.py
      |_config.ini

config.ini

; config.ini
[DEFAULT]
SECRET_KEY = secret-key-of-myapp

main.py:

    config = configparser.ConfigParser()
    config.read('config.ini')
    print('==>', config.sections())
    secret_key = config['DEFAULT']['SECRET_KEY']
    print(secret_key)

我收到此错误

  raise KeyError(key)
KeyError: 'SECRET_KEY'

1 个答案:

答案 0 :(得分:0)

当我运行程序时,它为我提供了以下内容。我使用python 3.7进行测试。 参考:https://docs.python.org/3/library/configparser.html

import configparser

config = configparser.ConfigParser()
config.read('config.ini')
print('==>', config.__dict__)
secret_key = config['DEFAULT']['SECRET_KEY']
print(secret_key)



> ==> {'_dict': <class 'collections.OrderedDict'>, '_sections': OrderedDict(), '_defaults': OrderedDict([('secret_key',
> 'secret-key-of-myapp')]), '_converters':
> <configparser.ConverterMapping object at 0x00000000020645C0>,
> '_proxies': OrderedDict([('DEFAULT', <Section: DEFAULT>)]),
> '_delimiters': ('=', ':'), '_optcre': re.compile('\n       
> (?P<option>.*?)                    # very permissive!\n       
> \\s*(?P<vi>=|:)\\s*              # any number of space/tab,\n         
> # followed by any of t, re.VERBOSE), '_comment_prefixes': ('#', ';'), '_inline_comment_prefixes': (), '_strict': True, '_allow_no_value':
> False, '_empty_lines_in_values': True, 'default_section': 'DEFAULT',
> '_interpolation': <configparser.BasicInterpolation object at
> 0x0000000002B9FA90>} secret-key-of-myapp