Py学习  »  Python

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

Crash Edwards • 3 年前 • 1275 次点击  

我有一个包含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
 
1275 次点击  
文章 [ 2 ]  |  最新文章 3 年前