【问题标题】:Parse config file of unknown length解析未知长度的配置文件
【发布时间】:2014-06-14 02:03:35
【问题描述】:

我是一个遇到了一些障碍的蟒蛇菜鸟。我需要导入一个配置文件才能使程序工作。我当然使用的是configparser,但这是我遇到的问题,无法弄清楚。我的配置文件看起来像这样

[Book1]
title = "Hello World"
status = "in"
location = "s2v14"

[Book2]
....

这将无限期地继续下去。我的问题是,如果我不知道该部分是什么,甚至不知道将存在多少个部分,我该如何解析配置文件。这个应用程序的目的是让我在图书状态从 out 变为 in 时收到一条消息,并显示与该部分相关的所有其他数据。

【问题讨论】:

  • 显然我的格式不正确,无法正常显示。配置文件每行有一个变量
  • 为什么要为值添加双引号?在配置文件中,您永远不需要这样做。只需添加例如:title = Hello World

标签: python parsing configuration-files


【解决方案1】:

通常使用某种循环来处理未知或可变数量的事物。在这种情况下,可以使用由找到的部分数量控制的forloop,因为在ConfigParser 实例对象读取并解析文件之后,它们和它们的数量都是已知的:

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)

如果这是输入文件:

[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"

请注意,您的字符串中有实际的引号字符串分隔符,当您打印它们时将可见......这不是在配置文件中存储字符串的常用方式。如果您无法更改配置文件的生成方式,那么根据您的操作,您可能需要在ConfigParserobject(使用value = value.strip('"'))读入它们后手动删除它们.

另一种方法是将整个配置文件转换为字典,如 answer 所示,转换为关于将ConfigParser.items转换为字典字典的问题,然后可以通过循环遍历字典的内容再次处理一个forloop。

【讨论】:

    【解决方案2】:

    对于结构未知的配置文件。

    假设您已经将文件加载到名为 config 的解析器中。

    获取可用部分的列表:

    config.sections()
    

    知道section后,获取键值对列表:

    config.items('Book1')
    

    documentation

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-16
      • 2021-08-14
      • 2016-03-12
      • 1970-01-01
      相关资源
      最近更新 更多