[英]Configparser set with no section
有没有办法让python中的configparser 设置一个值而不在配置文件中有部分?
如果没有,请告诉我任何替代方案。
谢谢。
更多信息:所以基本上我有一个格式的配置文件: Name: value
这是一个系统文件,我想更改给定名称的值。 我想知道是否可以使用模块轻松完成此操作,而不是手动编写解析器。
您可以使用csv
模块完成解析文件的大部分工作,并在进行更改后将其写回 - 因此它应该相对容易使用。 我从一个答案中得到了一个想法,题目是使用Python的ConfigParser来读取没有部分名称的文件 。
然而,我进行了一些更改,包括将其编码为在Python 2和3中工作,对键/值分隔符进行解密,因此它几乎可以是任何东西(但默认为冒号),以及几个优化。
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()
我知道无法用configparser做到这一点,这是非常面向部分的。
另一种方法是使用Michael Foord命名为ConfigObj的Voidspace Python模块。 在他撰写的题为“ ConfigObj简介 ”的文章的ConfigObj部分中,它说:
ConfigObj的最大优点是简单。 即使对于需要几个键值对的简单配置文件,ConfigParser也要求它们位于“部分”内。 ConfigObj没有这个限制 ,并且已经将配置文件读入内存,访问成员非常容易。
强调我的。
我个人喜欢将配置文件作为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验证(使用模式)在运行时之前查找错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.