我有一个包含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
}
}
这很完美,但是我如何创建具有相同数据的变量呢
若您想要一个所需行的列表,那个么创建一个空列表并添加每个相关行
如果你想输出一个字符串,你可以
如果您想收集dict中每个标题的输出,请参阅上面的“DarkKnight”注释
你可以这样做:-
相关问题 更多 >
编程相关推荐