【问题标题】:Python Write Dictionary Contents to ConfigParserPython 将字典内容写入 ConfigParser
【发布时间】:2013-04-09 18:37:06
【问题描述】:

我正在尝试将字典的内容写入 (然后读入) 到 ConfigParser,并且我相信我根据 docs 正确地做到了,但似乎无法得到它去工作。有人可以帮忙吗?

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

【问题讨论】:

  • 模块 configparser 与 ConfigParser 不同。该文档适用于 python 3.4,您运行的是哪个 python 版本?

标签: python dictionary configparser


【解决方案1】:

您正在阅读 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)

【讨论】:

    猜你喜欢
    • 2020-04-28
    • 1970-01-01
    • 1970-01-01
    • 2021-05-15
    • 2017-09-26
    • 1970-01-01
    • 1970-01-01
    • 2012-11-04
    • 2020-10-21
    相关资源
    最近更新 更多