我考虑使用for循环读取文件,但我只想读取特定的块。然后转换成JSON格式。
例如:
# Summary Report #######################
System time | 2020-02-27 15:35:32 UTC (local TZ: UTC +0000)
# Instances ##################################################
Port Data Directory Nice OOM Socket
===== ========================== ==== === ======
0 0
# Configuration File #########################################
Config File | /etc/srv.cnf
[server]
server_id = 1
port = 3016
tmpdir = /tmp
[client]
port = 3016
# management library ##################################
# The End ####################################################
捕获特定块:
[server]
server_id = 1
port = 3016
tmpdir = /tmp
[client]
port = 3016
生成的json是:
{
"server": {
"server_id":"1",
"port":"3016",
"tmpdir":"/tmp"
},
"client": {
"port": "3016"
}
}
是否有任何内置功能来实现这一点
我尝试使用以下方法来解析文本文件。但它没有起作用
import json filename = 'conf.txt' commands = {} with open(filename) as fh: for line in fh: command, description = line.strip().split('=', 1) commands[command.rstrip()] = description.strip() print(json.dumps(commands, indent=2, sort_keys=True))
您可以通过以下方式读取文件句柄中的所有行
下一部分是将所选行处理为json
首先,不要发布截图,使用编辑器键入文本
您必须根据您的需求进行编辑,它会根据您的样本进行一些假设
示例_input.txt
代码.py
相关问题 更多 >
编程相关推荐