Python 没有节的Configparser集
python中的configparser有没有一种方法可以在配置文件中没有节的情况下设置值 如果没有,请告诉我其他的选择 多谢各位 更多信息: 基本上我有一个配置文件,格式如下:Python 没有节的Configparser集,python,python-2.7,configparser,Python,Python 2.7,Configparser,python中的configparser有没有一种方法可以在配置文件中没有节的情况下设置值 如果没有,请告诉我其他的选择 多谢各位 更多信息: 基本上我有一个配置文件,格式如下: Name:value 这是一个系统文件,我想更改给定名称的值。我想知道是否可以用一个模块而不是手动编写解析器来轻松完成这项工作。我不知道用configparser来完成这项工作,configparser是非常面向小节的 另一种方法是使用michaelfoord命名的Python模块。在他写的一篇文章的标题部分,它说:
Name:value
这是一个系统文件,我想更改给定名称的值。我想知道是否可以用一个模块而不是手动编写解析器来轻松完成这项工作。我不知道用configparser来完成这项工作,configparser是非常面向小节的 另一种方法是使用michaelfoord命名的Python模块。在他写的一篇文章的标题部分,它说: 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>
现在,如果我们查看config.xml,我们会看到:
占边
1974年8月12日
英语
它的好处与普通XML的好处相同——它是人类可读的,在您可以想象的几乎每种编程语言中都已经存在许多像样的解析器,并且它支持分组和属性。当您的配置文件变大时,您还可以加入XML验证(使用模式)以在运行前发现错误。您可以使用
csv
模块来完成解析文件并在进行更改后将其写回的大部分工作,因此它应该相对容易使用。我是从一个学生那里得到这个想法的,他问了一个类似的问题,题目是
不过,我对它做了一些更改,包括将其编码为在Python2和Python3中都能使用,对它使用的键/值分隔符进行了非硬编码,使其几乎可以是任何东西(默认情况下可以是冒号),以及一些优化
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()
来自main()测试函数的uuu future uuu uu导入打印函数。
导入csv
导入系统
PY3=sys.version\u info.major>2
def read_属性(文件名,分隔符=':'):
“”“读取给定的属性文件,每行的格式为:
keyvalue。默认分隔符为“:”。
返回包含对的字典。
filename——要读取的文件的名称
"""
如果PY3 else dict(mode='rb',则打开\u kwargs=dict(mode='r',换行符=“”)
将open(文件名,**open_kwargs)作为csvfile:
reader=csv.reader(csvfile,delimiter=delimiter,escapechar='\\',
quoting=csv。QUOTE_无)
返回{行[0]:读卡器中行的行[1]
def write_属性(文件名、字典、分隔符=':'):
“”“将提供的字典按键排序顺序写入属性。”
文件的每行格式为:keyvalue
默认分隔符为“:”。
filename——要写入的文件的名称
字典——包含键/值对的字典。
"""
如果PY3 else dict(mode='wb',则打开_kwargs=dict(mode='w',换行符=“”)
将open(文件名,**open_kwargs)作为csvfile:
writer=csv.writer(csvfile,delimiter=delimiter,escapechar='\\',
quoting=csv。QUOTE_无)
writer.writerows(已排序(dictionary.items()))
def main():
数据={
‘答案’:‘6*7=42’,
‘骑士’:‘尼!’,
“垃圾邮件”:“鸡蛋”,
}
filename='test.properties'
写入属性(文件名、数据)#从数据字典创建csv。
newdata=read_properties(filename)#将其读回新词典。
打印('属性读取:')
打印(新数据)
打印()
#显示文件的实际内容。
以open(文件名“rb”)作为propfile:
contents=propfile.read().decode()
打印('文件包含:(%d字节)'%len(内容))
打印('内容:',报告(内容))
打印()
#测试是否正在保留数据。
打印(['Failure!'、'Success!'][data==newdata])
如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
main()
事实上我没有这个能力。我已经有一个.conf文件,其中的值的格式类似于“name:value”,我试图修改它们。@Haros:你用什么来读取你已经有的.config文件?@Haros关于其他方法的任何约束都应该添加到问题中。谢谢你提供的信息。您知道默认情况下Python中是否已有其他模块吗?ConfigParser主要用于从文件中读取设置,但听起来您想添加或更改其中一个模块的内容,对吗?这是一个比仅仅让它读取没有任何节的文件更困难的问题……更改
PY3=sys.version_info[0]>2
使其符合Python 2.6.6、Python 3.4.1和Jython 2.7b2。在该版本的Jythonsys中,version\u info
返回一个元组。谢谢你的代码。@martineau:这个解决方案真的很有帮助。我可以读取我可以写入和附加的数据。如果您能够提供编辑配置文件的解决方案,这将非常有用。例如,假设我已经通过每次使用您的方法添加一些用户到sshd_config文件中。现在我想删除一个用户及其相应的设置,然后我应该使用什么方法。请帮忙。如果你没有收到我的问题,也请告诉我。谢谢。@AbhishekVerma:这个答案中的函数是以字典格式传递和返回数据的,所以似乎您应该能够通过修改字典来完成您想要的操作,尽管我不熟悉sshd_config文件格式。无论如何,如果你不知道怎么做,我建议你发一个新问题。
<config>
<name>Jim Beam</name>
<dob>12th August 1974</dob>
<nationality>English</nationality>
</config>
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()