我在PyCharm中有一个python项目,我有一个以下目录结构:
MyProject
|_d1
|_d2
|_d3
|_Main.py
|_config.ini
config.ini文件
; config.ini
[DEFAULT]
SECRET_KEY = secret-key-of-myapp
卖弄.朋友:
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'
当我运行程序时,它给了我以下内容。我使用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