簡體   English   中英

Python將字典內容寫入ConfigParser

[英]Python Write Dictionary Contents to ConfigParser

我正在嘗試將字典的內容寫入(並稍后讀入)到ConfigParser,我相信我正在根據文檔正確地進行,但似乎無法讓它工作。 有人可以幫忙嗎?

import ConfigParser
parser = ConfigParser.ConfigParser()

parser['User_Info'] = {"User1-votes":"36","User1-gamestart":"13232323","User2-votes":"36","User2-gamestart":"234234234","User3-votes":"36","User3-gamestart":"13232323"}

Traceback (most recent call last):   File "<stdin>", line 1, in
<module> AttributeError: ConfigParser instance has no attribute '__setitem__'

我正在尋找的是有一個我可以更新的字典,並在最后寫入配置文件,所以它看起來像:

[User_Info]
User1-gamestart = 13232323
User3-votes = 36
User2-votes = 36
User1-votes = 36
User2-gamestart = 234234234
User3-gamestart = 13232323

您正在閱讀python 3.4的文檔,但您可能正在使用舊版本的python。

以下是如何在舊版本的python中使用ConfigParser:

import ConfigParser
parser = ConfigParser.ConfigParser()

info = {"User1-votes":"36","User1-gamestart":"13232323","User2-votes":"36","User2-gamestart":"234234234","User3-votes":"36","User3-gamestart":"13232323"}

parser.add_section('User-Info')
for key in info.keys():
    parser.set('User-Info', key, info[key])

with open('config.ini', 'w') as f:
    parser.write(f)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM