簡體   English   中英

python從配置文件中提取值

[英]python extract value from config file

我知道,有著名的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”的值? 由於我需要多次處理配置文件,因此我只是在尋找這種格式的最簡單方法。

如果您可以將其作為常規文件讀取,請使用:

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

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"
    }
}

注意:如果可能,請使用正確的JSON作為配置文件。 使用JSON是不安全的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM