[英]ConfigParser - get entire section as dict and set values
我想要做的(理想)是使用with
用字典一次設置的參數一整節。 經過一些試驗,我想出了以下代碼,它引發了AttributeError
:
import configparser
import os
CONFIG_PATH = os.path.abspath(os.path.dirname(__file__)) + '/config.ini'
config = configparser.ConfigParser()
assert open(CONFIG_PATH)
config.read(CONFIG_PATH)
with dict(config.items('Settings')) as c:
c['username'] = input('Enter username: ')
config.ini 文件:
[Settings]
username = ''
回溯:
Traceback (most recent call last):
File "test.py", line 9, in <module>
with dict(config.items('Settings')) as c:
AttributeError: __enter__
我覺得我在這里使用configparser
錯誤的,但我想寫一些漂亮的代碼來設置config.ini
參數。
你不能用一個字典, with
,因為字典不是一個上下文管理器。
with dict() as d:
print d
輸出:
Traceback (most recent call last):
File "Main.py", line 6, in <module>
with dict() as d:
AttributeError: __exit__
https://paiza.io/projects/aPGRmOEmydbJL2ZeRtF-3A?language=python
對象必須定義__enter__
和__exit__
才能用作上下文管理器。
文檔: http : //book.pythontips.com/en/latest/context_managers.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.