简体   繁体   中英

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.

"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? 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:

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:

"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. It is fail safe to use JSON.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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