使用Python将ini文件中的所有内容读取到字典中

发布于 2024-09-09 02:49:18 字数 483 浏览 1 评论 0原文

通常,我的代码如下,用于获取变量中的特定项目,如下所示

try:
    config = ConfigParser.ConfigParser()
    config.read(self.iniPathName)
except ConfigParser.MissingSectionHeaderError, e:
    raise WrongIniFormatError(`e`)

try:
    self.makeDB = config.get("DB","makeDB")
except ConfigParser.NoOptionError:
    self.makeDB = 0

有没有办法读取 python 字典中的所有内容?

例如

[A]
x=1
y=2
z=3
[B]
x=1
y=2
z=3

写入

val["A"]["x"] = 1
...
val["B"]["z"] = 3

Normally, I code as follows for getting a particular item in a variable as follows

try:
    config = ConfigParser.ConfigParser()
    config.read(self.iniPathName)
except ConfigParser.MissingSectionHeaderError, e:
    raise WrongIniFormatError(`e`)

try:
    self.makeDB = config.get("DB","makeDB")
except ConfigParser.NoOptionError:
    self.makeDB = 0

Is there any way to read all the contents in a python dictionary?

For example

[A]
x=1
y=2
z=3
[B]
x=1
y=2
z=3

is written into

val["A"]["x"] = 1
...
val["B"]["z"] = 3

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

小伙你站住 2024-09-16 02:49:19

另一件需要注意的事情是,ConfigParser 会将键值转换为小写,因此,如果您将配置条目转换为字典,请交叉检查您的要求。因此我遇到了一个问题。对我来说,我有驼峰式键,因此,当我开始使用字典而不是文件时,必须更改一些代码。 ConfigParser.get() 方法在内部将密钥转换为小写。

One more thing to take care is, ConfigParser converts the key values to lowercase hence in case you are converting the config entries to a dictionary cross check your requirements. I faced a problem because of this. For me I was having camel-case keys hence, had to change some amount of code when I started using the dictionary instead of files. ConfigParser.get() method internally converts the key to lower-case.

千纸鹤带着心事 2024-09-16 02:49:19

假设文件:config.properties 包含以下内容:

  • k =v
  • k2= v2
  • k3= v3

Python 代码:

def read_config_file(file_path):
        with open(file=file_path, mode='r') as fs:
            return {k.strip(): v.strip() for i in [l for l in fs.readlines() if l.strip() != ''] for k, v in [i.split('=')]}


print('file as dic: ', read_config_file('config.properties'))

suppose file: config.properties contains the following:

  • k =v
  • k2= v2
  • k3= v3

python code:

def read_config_file(file_path):
        with open(file=file_path, mode='r') as fs:
            return {k.strip(): v.strip() for i in [l for l in fs.readlines() if l.strip() != ''] for k, v in [i.split('=')]}


print('file as dic: ', read_config_file('config.properties'))
感悟人生的甜 2024-09-16 02:49:19

来自 https://wiki.python.org/moin/ConfigParserExamples

def ConfigSectionMap(section):
dict1 = {}
options = Config.options(section)
for option in options:
    try:
        dict1[option] = Config.get(section, option)
        if dict1[option] == -1:
            DebugPrint("skip: %s" % option)
    except:
        print("exception on %s!" % option)
        dict1[option] = None
return dict1

from https://wiki.python.org/moin/ConfigParserExamples

def ConfigSectionMap(section):
dict1 = {}
options = Config.options(section)
for option in options:
    try:
        dict1[option] = Config.get(section, option)
        if dict1[option] == -1:
            DebugPrint("skip: %s" % option)
    except:
        print("exception on %s!" % option)
        dict1[option] = None
return dict1
彩虹直至黑白 2024-09-16 02:49:18

我建议子类化 ConfigParser.ConfigParser (或 SafeConfigParser, &c)以安全地访问“受保护”属性(以单下划线开头的名称 - “private”将是名称以两个下划线开头,即使在子类中也不能访问...):

import ConfigParser

class MyParser(ConfigParser.ConfigParser):

    def as_dict(self):
        d = dict(self._sections)
        for k in d:
            d[k] = dict(self._defaults, **d[k])
            d[k].pop('__name__', None)
        return d

这模拟了配置解析器的通常逻辑,并且保证在有 ConfigParser 的所有 Python 版本中工作.py 模块(最高 2.7,这是 2.* 系列的最后一个 - 知道未来不会有 Python 2.any 版本,这就是兼容性的 >保证;-)。

如果您需要支持未来的 Python 3.* 版本(最高为 3.1,可能还有即将推出的 3.2),只需将模块重命名为全小写的 configparser 即可当然)几年后它可能需要一些关注/调整,但我不期望发生任何重大的事情。

I suggest subclassing ConfigParser.ConfigParser (or SafeConfigParser, &c) to safely access the "protected" attributes (names starting with single underscore -- "private" would be names starting with two underscores, not to be accessed even in subclasses...):

import ConfigParser

class MyParser(ConfigParser.ConfigParser):

    def as_dict(self):
        d = dict(self._sections)
        for k in d:
            d[k] = dict(self._defaults, **d[k])
            d[k].pop('__name__', None)
        return d

This emulates the usual logic of config parsers, and is guaranteed to work in all versions of Python where there's a ConfigParser.py module (up to 2.7, which is the last of the 2.* series -- knowing that there will be no future Python 2.any versions is how compatibility can be guaranteed;-).

If you need to support future Python 3.* versions (up to 3.1 and probably the soon forthcoming 3.2 it should be fine, just renaming the module to all-lowercase configparser instead of course) it may need some attention/tweaks a few years down the road, but I wouldn't expect anything major.

权谋诡计 2024-09-16 02:49:18

我设法得到了答案,但我希望应该有更好的答案。

dictionary = {}
for section in config.sections():
    dictionary[section] = {}
    for option in config.options(section):
        dictionary[section][option] = config.get(section, option)

I managed to get an answer, but I expect there should be a better one.

dictionary = {}
for section in config.sections():
    dictionary[section] = {}
    for option in config.options(section):
        dictionary[section][option] = config.get(section, option)
岁月静好 2024-09-16 02:49:18

我知道这个问题是 5 年前提出的,但今天我把这个 dict 理解变成了这样:

parser = ConfigParser()
parser.read(filename)
confdict = {section: dict(parser.items(section)) for section in parser.sections()}

I know that this question was asked 5 years ago, but today I've made this dict comprehension thingy:

parser = ConfigParser()
parser.read(filename)
confdict = {section: dict(parser.items(section)) for section in parser.sections()}
微暖i 2024-09-16 02:49:18

ConfigParser 的实例数据在内部存储为嵌套字典。您可以复制它,而不是重新创建它。

>>> import ConfigParser
>>> p = ConfigParser.ConfigParser()
>>> p.read("sample_config.ini")
['sample_config.ini']
>>> p.__dict__
{'_defaults': {}, '_sections': {'A': {'y': '2', '__name__': 'A', 'z': '3', 'x': '1'}, 'B':         {'y': '2', '__name__': 'B', 'z': '3', 'x': '1'}}, '_dict': <type 'dict'>}
>>> d = p.__dict__['_sections'].copy()
>>> d
{'A': {'y': '2', '__name__': 'A', 'z': '3', 'x': '1'}, 'B': {'y': '2', '__name__': 'B', 'z': '3', 'x': '1'}}

编辑:

Alex Martelli 的 解决方案更干净、更健壮、更漂亮。虽然这是公认的答案,但我建议改用他的方法。有关更多信息,请参阅他对此解决方案的评论。

The instance data for ConfigParser is stored internally as a nested dict. Instead of recreating it, you could just copy it.

>>> import ConfigParser
>>> p = ConfigParser.ConfigParser()
>>> p.read("sample_config.ini")
['sample_config.ini']
>>> p.__dict__
{'_defaults': {}, '_sections': {'A': {'y': '2', '__name__': 'A', 'z': '3', 'x': '1'}, 'B':         {'y': '2', '__name__': 'B', 'z': '3', 'x': '1'}}, '_dict': <type 'dict'>}
>>> d = p.__dict__['_sections'].copy()
>>> d
{'A': {'y': '2', '__name__': 'A', 'z': '3', 'x': '1'}, 'B': {'y': '2', '__name__': 'B', 'z': '3', 'x': '1'}}

Edit:

Alex Martelli's solution is cleaner, more robust, and prettier. While this was the accepted answer, I'd suggest using his approach instead. See his comment to this solution for more info.

一念一轮回 2024-09-16 02:49:18

如何在py中解析ini文件?

import ConfigParser
config = ConfigParser.ConfigParser()
config.read('/var/tmp/test.ini')
print config.get('DEFAULT', 'network')

其中 test.ini 文件包含:

[DEFAULT]
network=shutup
others=talk

How to parse ini file in py?

import ConfigParser
config = ConfigParser.ConfigParser()
config.read('/var/tmp/test.ini')
print config.get('DEFAULT', 'network')

Where test.ini file contain:

[DEFAULT]
network=shutup
others=talk
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文