Python提取配置文件中的值

2024-09-30 05:17:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道,有著名的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”的值?由于我需要多次处理配置文件,所以我正在寻找这种格式的最简单方法。在


Tags: name解析器server格式counterglobalappidstrike
2条回答

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

输出:

^{pr2}$

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.JSON文件。使用JSON是安全的。在

如果可以将其作为常规文件读取,请使用:

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

相关问题 更多 >

    热门问题