[英]Unable to get key from ConfigParser value
我在同一個文件夾中創建了.txt 文件來存儲 Api 密鑰、用戶名等...如圖 1 所示
在圖 2 中,您會發現我是如何輸入信息的(使用 = 而沒有 '')
使用此代碼,我嘗試將 .txt 文件中的數據導入代碼(圖 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']
正如您在圖 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'
我做錯了什么?
您在config.read()
中給出了錯誤的路徑。
嘗試絕對路徑,它應該工作
config = configparser.ConfigParser()
config.read("/path/to/config.ini")
使用實際路徑,您可以通過右鍵單擊此文件獲得。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.