4

python中的configparser有没有办法在配置文件中没有部分的情况下设置一个值?

如果没有,请告诉我任何替代方案。

谢谢你。

更多信息: 所以基本上我有一个格式为的配置文件: Name: value 这是一个系统文件,我想更改给定名称的值。我想知道这是否可以通过模块轻松完成,而不是手动编写解析器。

4

3 回答 3

3

您可以使用该csv模块完成大部分解析文件的工作,并在您进行更改后将其写回——因此它应该相对易于使用。我从一个名为Using ConfigParser to read a file without section name的类似问题的答案中得到了这个想法。

但是我已经对其进行了一些更改,包括对其进行编码以在 Python 2 和 3 中工作,对它使用的键/值分隔符进行非硬编码,因此它几乎可以是任何东西(但默认情况下是冒号),以及几个优化。

from __future__ import print_function  # For main() test function.
import csv
import sys
PY3 = sys.version_info.major > 2


def read_properties(filename, delimiter=':'):
    """ Reads a given properties file with each line in the format:
        key<delimiter>value. The default delimiter is ':'.

        Returns a dictionary containing the pairs.

            filename -- the name of the file to be read
    """
    open_kwargs = dict(mode='r', newline='') if PY3 else dict(mode='rb')

    with open(filename, **open_kwargs) as csvfile:
        reader = csv.reader(csvfile, delimiter=delimiter, escapechar='\\',
                            quoting=csv.QUOTE_NONE)
        return {row[0]: row[1] for row in reader}


def write_properties(filename, dictionary, delimiter=':'):
    """ Writes the provided dictionary in key-sorted order to a properties
        file with each line of the format: key<delimiter>value
        The default delimiter is ':'.

            filename -- the name of the file to be written
            dictionary -- a dictionary containing the key/value pairs.
    """
    open_kwargs = dict(mode='w', newline='') if PY3 else dict(mode='wb')

    with open(filename, **open_kwargs) as csvfile:
        writer = csv.writer(csvfile, delimiter=delimiter, escapechar='\\',
                            quoting=csv.QUOTE_NONE)
        writer.writerows(sorted(dictionary.items()))


def main():
    data = {
        'Answer': '6*7 = 42',
        'Knights': 'Ni!',
        'Spam': 'Eggs',
    }

    filename = 'test.properties'
    write_properties(filename, data)  # Create csv from data dictionary.

    newdata = read_properties(filename)  # Read it back into a new dictionary.
    print('Properties read: ')
    print(newdata)
    print()

    # Show the actual contents of file.
    with open(filename, 'rb') as propfile:
        contents = propfile.read().decode()
    print('File contains: (%d bytes)' % len(contents))
    print('contents:', repr(contents))
    print()

    # Tests whether data is being preserved.
    print(['Failure!', 'Success!'][data == newdata])

if __name__ == '__main__':
     main()
于 2013-07-22T20:12:15.787 回答
0

我不知道使用非常面向部分的 configparser 无法做到这一点。

另一种方法是使用Michael Foord 名为ConfigObj的Voidspace Python 模块。在他写的一篇题为An Introduction to ConfigObj的文章的 ConfigObj 的优势部分中,它说:

ConfigObj 的最大优点是简单。即使对于只需要几个键值对的琐碎配置文件,ConfigParser 也要求它们位于“部分”内。ConfigObj 没有这个限制,并且将配置文件读入内存后,访问成员非常容易。

强调我的。

于 2013-07-19T14:52:02.510 回答
-1

就我个人而言,我喜欢将我的配置文件作为 XML。一个示例(取自 ConfigObj 文章以进行比较)您可以创建一个名为config.xml的文件,其中包含以下内容:

<?xml version="1.0"?>
<config>
  <name>Michael Foord</name>
  <dob>12th August 1974</dob>
  <nationality>English</nationality>
</config>

在 Python 中,您可以通过以下方式获取值:

>>> import xml.etree.cElementTree as etree
>>> config = etree.parse("config.xml")
>>> config.find("name").text
'Michael Foord'
>>> config.find("name").text = "Jim Beam"
>>> config.write("config.xml")

现在,如果我们查看config.xml,我们会看到:

<config>
  <name>Jim Beam</name>
  <dob>12th August 1974</dob>
  <nationality>English</nationality>
</config>

优点与通用 XML 相同 - 它是人类可读的,在您能想象到的几乎所有编程语言中已经存在许多体面的解析器,并且它支持分组和属性。作为额外的好处,当您的配置文件变大时,您还可以合并 XML 验证(使用模式)以在运行前发现错误。

于 2013-07-19T17:51:16.520 回答