Configparser设置没有部分

时间:2013-07-19 13:42:39

标签: python python-2.7 configparser

有没有办法让python中的configparser 设置一个值而不在配置文件中有部分?

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

谢谢。

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

3 个答案:

答案 0 :(得分:2)

您可以使用csv模块完成解析文件的大部分工作,并在进行更改后将其写回 - 因此它应该相对容易使用。我从answer之一得到了一个题为Using Python's ConfigParser to read a file without section name的类似问题。

然而,我进行了一些更改,包括将其编码为Python 2& 3,unhardcoding键/值分隔符所以它几乎可以是任何东西(但默认是冒号),以及几个优化。

from __future__ import print_function # only for module main() test function
import csv
import sys
PY3 = sys.version_info[0] > 2

def read_properties(filename, delimiter=':'):
    ''' Reads a given properties file with each line of the format key=value.
        Returns a dictionary containing the pairs.
            filename -- the name of the file to be read
    '''
    open_kwargs = {'mode': 'r', 'newline': ''} if PY3 else {'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 in the format: key<delimiter>value
            filename -- the name of the file to be written
            dictionary -- a dictionary containing the key/value pairs.
    '''
    open_kwargs = {'mode': 'w', 'newline': ''} if PY3 else {'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)
    newdata = read_properties(filename)

    print('Read in: ')
    print(newdata)
    print()

    with open(filename, 'rb') as propfile:
        contents = propfile.read()
    print('File contents: (%d bytes)' % len(contents))
    print(repr(contents))

    print(['Failure!', 'Success!'][data == newdata])

if __name__ == '__main__':
     main()

答案 1 :(得分:0)

我知道无法用configparser这样做,这是非常面向部分的。

另一种方法是使用Michael Foord名为VoidspaceConfigObj Python模块。在他撰写的题为The Advantages of ConfigObj的文章的An Introduction to ConfigObj部分中,它说:

  

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

强调我的。

答案 2 :(得分:-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验证(使用模式)来查找错误。