Parse config file of unknown length

安稳与你 提交于 2020-01-15 12:15:28

问题


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.


回答1:


Typically one uses some kind of loop to to process an unknown or variable number of things. In this case aforloop 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"

This would be the output:

section: Book1
  title: "Hello World"
  status: "in"
  location: "s2v14"
section: Book2
  title: "Hello World II"
  status: "out"
  location: "s2v15"

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 theConfigParserobject (with avalue = value.strip('"')).

Another approach would be to convert the entire configuration file into a dictionary as illustrated by this answer to a question about convertingConfigParser.itemsinto a dictionary of dictionaries which afterwards could again be processed by looping over the dictionaries' content using aforloop.




回答2:


For config file with unknown structure.

Assuming you have already loaded the file into a parser named config.

Get a list of available sections:

config.sections()

After knowing the section, get the list of key value pairs:

config.items('Book1')

documentation



来源:https://stackoverflow.com/questions/24215971/parse-config-file-of-unknown-length

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!