python从配置文件中提取值

时间:2017-05-07 17:40:12

标签: python python-2.7 configparser

我知道,有着名的python配置解析器,但我认为对于这种配置格式,解析器不是最佳选择。

"AppState"
{
    "appid"     "740"
    "Universe"      "1"
    "name"      "Counter-Strike Global Offensive - Dedicated Server"
    "StateFlags"        "4"
    "installdir"        "Counter-Strike Global Offensive Beta - Dedicated Server"
    "LastUpdated"       "1492880350"
    "UpdateResult"      "0"
    "SizeOnDisk"        "14563398502"
    "buildid"       "1771538"
    "LastOwner"     "76561202168992874"
    "BytesToDownload"       "6669177712"
    "BytesDownloaded"       "6669177712"
    "AutoUpdateBehavior"        "0"
    "AllowOtherDownloadsWhileRunning"       "0"
    "UserConfig"
    {
    }
    "MountedDepots"
    {
        "731"       "3148506631334968252"
        "740"       "8897003951704178635"
    }
}

例如如何以最佳方式提取“buildid”的值?由于我需要使用配置文件多次工作,我只是在寻找这种格式的最简单方法。

2 个答案:

答案 0 :(得分:0)

如果您可以将其作为常规文件使用:

import re
with open('myfile.extension') as data:
    for line in data:
        if 'buildid' in line:
            print re.findall('\d+', line)
            break

答案 1 :(得分:0)

Python 2解决方案:

with open("config.txt","r") as fp:
    line_list = [c.strip() for c in fp.readlines()]
    for line in line_list:
        if "buildid" in line:
            buildid = line.split()[1]
            print int(buildid[1:-1])
            break

输出:

1771538

config.txt包含:

"AppState"
{
    "appid"     "740"
    "Universe"      "1"
    "name"      "Counter-Strike Global Offensive - Dedicated Server"
    "StateFlags"        "4"
    "installdir"        "Counter-Strike Global Offensive Beta - Dedicated Server"
    "LastUpdated"       "1492880350"
    "UpdateResult"      "0"
    "SizeOnDisk"        "14563398502"
    "buildid"       "1771538"
    "LastOwner"     "76561202168992874"
    "BytesToDownload"       "6669177712"
    "BytesDownloaded"       "6669177712"
    "AutoUpdateBehavior"        "0"
    "AllowOtherDownloadsWhileRunning"       "0"
    "UserConfig"
    {
    }
    "MountedDepots"
    {
        "731"       "3148506631334968252"
        "740"       "8897003951704178635"
    }
}

N.B。:如果可能,请使用适当的JSON配置文件。使用JSON是安全的。