解析未知长度的配置文件 [英] Parse config file of unknown length
问题描述
我是一个Python菜鸟,遇到了一些障碍.我需要导入配置文件以使程序正常工作.我当然在使用configparser,但这是我遇到的问题,无法弄清.我的配置文件看起来像这样
I am a python noob that has hit a bit of a snag. I need to import a config file to make a program work. I am using the configparser of course but here is the problem I am having and can not figure out. My config file will look something like this
[Book1]
title = "Hello World"
status = "in"
location = "s2v14"
[Book2]
....
,这将不确定地继续.我的问题是,如果我不知道该节是什么,甚至不知道将存在多少个节,该如何解析配置文件.这个应用程序的目的是让我可以在图书状态从外"变为内"时收到一条消息,并显示与该部分相关的所有其他数据.
and this will continue indefinately. My problem is how do I parse the config file if I dont know what the section is or even how many sections will exist. The purpose of this app would be to allow me to receive a message when a book status changed from out to in and also display all other data associated with the section.
推荐答案
通常,人们使用某种循环来处理未知数或可变数的事物.在这种情况下,可以使用由找到的节数控制的for
循环,因为在ConfigParser
实例对象读取并解析了文件之后,它们和它们的数目都是已知的:
Typically one uses some kind of loop to to process an unknown or variable number of things. In this case afor
loop controlled by number of sections found could be used because after theConfigParser
instance object has read and parsed the file, they and the number of them are all known:
config = ConfigParser.ConfigParser()
with open('unknown.cfg') as cfg_file:
config.readfp(cfg_file) # read and parse entire file
for section in config.sections():
print 'section:', section
for option, value in config.items(section):
print ' {}: {}'.format(option, value)
因此,如果这是输入文件:
So if this was the input file:
[Book1]
title = "Hello World"
status = "in"
location = "s2v14"
[Book2]
title = "Hello World II"
status = "out"
location = "s2v15"
这将是输出:
section: Book1
title: "Hello World"
status: "in"
location: "s2v14"
section: Book2
title: "Hello World II"
status: "out"
location: "s2v15"
请注意,您的字符串中包含实际的引号字符串定界符,当您打印它们时将可见这些定界符...这不是在配置文件中存储字符串的常用方法.如果您无法更改配置文件的生成方式,那么根据您的操作,您可能需要在ConfigParser
对象(使用a value = value.strip('"')
)读取它们之后手动将其删除.
Note that your strings have actual quote string delimiters in them which will be visible when you print them...which is not the usual way of storing strings in configuration files. If you can't change the way the configuration files are generated, then depending on what you're doing, you may need to manually remove them after they've been read in by theConfigParser
object (with avalue = value.strip('"')
).
另一种方法是将整个配置文件转换为字典,如该答案所示,将其转换为有关转换的问题ConfigParser.items
放入词典字典中,然后可以通过使用for
loop遍历词典的内容来再次对其进行处理.
Another approach would be to convert the entire configuration file into a dictionary as illustrated by this answer to a question about convertingConfigParser.items
into a dictionary of dictionaries which afterwards could again be processed by looping over the dictionaries' content using afor
loop.
这篇关于解析未知长度的配置文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!