简体   繁体   中英

Unable to get key from ConfigParser value

  1. I create.txt file inside the same folder to store Api Key, user name, etc... as you can see in Image 1

  2. in Image 2 you will find how I enter the info (Using = and no '')

  3. With this code I´m trying to import data from the.txt file into the code (Image 3):

     config = configparser.ConfigParser() config.read("config.ini") api_id = config['Telegram']['api_id'] api_hash = config['Telegram']['api_hash'] api_hash = str(api_hash) phone = config['Telegram']['phone'] username = config['Telegram']['username']

And I´m getting the next error as you can see in Image 3.

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-31-26acbcbbad1b> in <module>
      4 
      5 # Setting configuration values
----> 6 api_id = config['Telegram']['api_id']
      7 api_hash = config['Telegram']['api_hash']
      8 

/opt/anaconda3/lib/python3.7/configparser.py in __getitem__(self, key)
    956     def __getitem__(self, key):
    957         if key != self.default_section and not self.has_section(key):
--> 958             raise KeyError(key)
    959         return self._proxies[key]
    960 

KeyError: 'Telegram'

What I´m doing wrong?

图 1

图 2

图 3

You are giving wrong path in config.read() .

Try absolute path, It should work

config = configparser.ConfigParser()
config.read("/path/to/config.ini")

Use the actual path, which you can get from right click on this file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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