简体   繁体   English

python从配置文件中提取值

[英]python extract value from config file

I know, there's the famous python config parser, but I think for this kind of config format, the parser will not be the best choice. 我知道,有著名的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"
    }
}

For example how to extract the value of "buildid" in the best way? 例如,如何以最佳方式提取“ buildid”的值? Since I need to work many times with config files, I'm just searching for the easiest way for this kind of format. 由于我需要多次处理配置文件,因此我只是在寻找这种格式的最简单方法。

If you can read it as a regular file use: 如果您可以将其作为常规文件读取,请使用:

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

Python 2 Solution: 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

Output: 输出:

1771538

config.txt contains: 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"
    }
}

NB: If possible use proper JSON for configuration file. 注意:如果可能,请使用正确的JSON作为配置文件。 It is fail safe to use JSON. 使用JSON是不安全的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM