简体   繁体   English

无法使用 configparser 从 .ini 文件中读取

[英]Can't read from .ini file using configparser

I recently started learning python and I'm getting this issue where, using configparser to read a key from an ini file, it keep raising a key error.我最近开始学习 python,我遇到了这个问题,使用 configparser 从 ini 文件中读取密钥,它不断引发密钥错误。

I have two files:我有两个文件:

weather.py天气.py

import configparser

def get_api_key():
    config = configparser.ConfigParser()
    config.read('config.ini')
    return config['openweathermap']['api_key']

print(get_api_key())

and config.ini和 config.ini

[openweathermap]
api_key=e53647dc71abcf81c779b83f1a8807c1

both files are placed in the same folder.这两个文件都放在同一个文件夹中。

using print(get_api_key()) gives me this error:使用print(get_api_key())给我这个错误:

Traceback (most recent call last):
  File "...\weather.py", line 8, in <module>
    print(get_api_key())
  File "...\weather.py", line 6, in get_api_key
    return config['openweathermap']['api_key']
  File "C:\Users\username\AppData\Local\Programs\Python\Python310\lib\configparser.py", line 964, in __getitem__
    raise KeyError(key)
KeyError: 'openweathermap'

Would it be possible to get some help?是否有可能得到一些帮助? Thanks in advance.提前致谢。

Edit : "balderman" asked me to show that both files are in the same directory,so I cd 'd into the folder and used ls :编辑:“balderman”要求我显示两个文件都在同一个目录中,所以我cd进入文件夹并使用ls

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
d-----         13-Nov-21     22:31                __pycache__
-a----         13-Nov-21     23:03              0 config.ini
-a----         13-Nov-21     23:03            737 weather.py

For me, it worked when I changed the file path with r"<filePath>"对我来说,当我用r"<filePath>"更改文件路径时它起作用了

config = configparser.RawConfigParser()
config.read(r"..\Configurations\config.ini")

I hope this works.我希望这行得通。

import configparser

def get_api_key():
    config = configparser.ConfigParser()
    config.read('config.ini')
    return config.get('openweathermap','api_key')

print(get_api_key())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM