【问题标题】:Parse config file and create json object using Python使用 Python 解析配置文件并创建 json 对象
【发布时间】:2021-04-16 22:53:35
【问题描述】:

我有一个配置文件目录,每个配置文件都有这样一行:

DOMAIN domainname.com

我需要能够提取DOMAIN 之后的所有内容并将其存储在 json 对象中。

我可以像这样匹配我需要的行:

d = re.findall(^DOMAIN.*, mystring)

我可以像这样将它添加到字典中:

dict = {
       "config": {
            "domains": [
               d,
            ]
        }
}

这有效,但仅适用于第一个 DOMAIN。如何找到所有出现的DOMAIN 并将其添加到domains 数组中?

【问题讨论】:

  • “仅适用于第一个 DOMAIN”是什么意思?还有哪些其他 DOMAIN?
  • 如果我理解正确,只需要一个附加属性。 domains = re.findall(r'^DOMAIN\s+(.*)$', mystring, flags=re.M)

标签: python json


【解决方案1】:

假设所有这些域配置文件都在 config 目录中,其中仅包含像 DOMAIN <domain> 这样的单行文件,您可以执行以下操作:

import os

domains = []
for file in os.listdir('./config'):
    with open(file) as f:
        _, d = f.read().strip().split()
        domains.append(d)

然后你在这个字典里设置domains的值

【讨论】:

    猜你喜欢
    • 2012-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-25
    • 2014-12-25
    相关资源
    最近更新 更多