Py学习  »  Python

在Python中读取带有标题的文本文件,并仅将指定标题下的数据检索到变量中

Crash Edwards • 3 年前 • 1274 次点击  

我有一个包含json和已知标题名的文本文件。

例子:

[header0]
{
  "IPMI": {
      "ProtocolEnabled": true,
      "Port": 623
  },
  "SSH": {
      "ProtocolEnabled": true,
      "Port": 22
  }
}
[header1]
{
  "GraphicalConsole": {
      "ServiceEnabled": true,
      "MaxConcurrentSessions": 2
  }
}
[header2]
{
  "InterfaceEnabled": true,
  "SignalType": "Rs232",
  "BitRate": "115200",
  "Parity": "None",
  "DataBits": "8",
  "StopBits": "1"
}

我试图在特定的头下创建一个带有json的变量(有效负载),以便与请求模块一起使用。我可以循环打印数据,没有问题。

with open("test.txt") as f:
    for line in f:
        if line.startswith('[header1]'):  # beginning of section use first line
            for line in f:  # check for end of section breaking if we find the stop line
                if line.startswith("[header2]"):
                    break
                else:  # else process lines from section
                    print(line.rstrip("\n"))

哪些输出:

{
  "GraphicalConsole": {
      "ServiceEnabled": true,
      "MaxConcurrentSessions": 2
  }
}

这很完美,但我如何创建具有相同数据的变量?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/132669
 
1274 次点击  
文章 [ 2 ]  |  最新文章 3 年前
user2668284 user2668284
Reply   •   1 楼
user2668284 user2668284    4 年前

你可以这样做:-

import json

def main(filename):
    payload = {}
    ch = None
    jt = []
    with open(filename) as txt:
        for line in txt.readlines():
            if line.startswith('['):
                if ch and jt:
                    payload[ch] = json.loads(''.join(jt))
                    jt = []
                ch = line[1:line.index(']')]
            else:
                jt.append(line.strip())
        if ch and jt:
            payload[ch]=json.loads(''.join(jt))
    print(json.dumps(payload, indent=4))


if __name__ == '__main__':
    main('test.txt')
Sean C
Reply   •   2 楼
Sean C    4 年前

如果您想要一个所需行的列表,那么创建一个空列表并添加每个相关行

with open("test.txt") as f:
reslist = []
for line in f:
    if line.startswith('[header1]'):  # beginning of section use first line
        for line in f:  # check for end of section breaking if we find the stop line
            if line.startswith("[header2]"):
                break
            else:  # else process lines from section
                print(line.rstrip("\n"))
                reslist.append(line)
return reslist

如果你想输出一个字符串,你可以。。。

resstring = '\n'.join(reslist)

如果您想收集dict中每个标题的输出,请参阅上面的“DarkKnight”评论