本文介绍了没有部分的 Configparser 集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

python 中的 configparser 有没有办法设置一个值而无需在配置文件中包含部分?

Is there a way for configparser in python to set a value without having sections in the config file?

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

If not please tell me of any alternatives.

谢谢.

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

more info:So basically I have a config file with format:Name: valueIt's a system file that I want to change the value for a given name. I was wondering if this can be done easily with a module instead of manually writing a parser.

推荐答案

您可以使用 csv 模块来完成解析文件并在进行更改后将其写回的大部分工作 --所以应该比较好用.我从 answers 到一个类似的问题,标题为 Using ConfigParser to read a没有节名的文件.

You could use the csv module to do most of work of parsing the file and writing it back out after you made changes -- so it should be relatively easy to use. I got the idea from one of the answers to a similar question titled Using ConfigParser to read a file without section name.

但是,我对其进行了许多更改,包括对其进行编码以在 Python 2 和3、对它使用的键/值分隔符进行硬编码,使其几乎可以是任何东西(但默认情况下是冒号),并进行了多项优化.

However I've made a number of changes to it, including coding it to work in both Python 2 & 3, unhardcoding the key/value delimiter it uses so it could be almost anything (but be a colon by default), along with several optimizations.

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()

这篇关于没有部分的 Configparser 集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 15:48