如何通过Python将设置行范围内的文本文件转换为json格式



我考虑使用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 ####################################################

txt文件

捕获特定块:

[server]
server_id            = 1
port                                = 3016
tmpdir                              = /tmp
[client]
port                                = 3016

块内容

生成的json是:

{
"server": {
"server_id":"1",
"port":"3016",
"tmpdir":"/tmp"
},
"client": {
"port": "3016"
}
}

生成的json

有什么内置功能可以实现这一点吗?

我尝试使用以下内容来解析文本文件。但这并没有奏效。

导入jsonfilename="conf.txt"命令={}open(filename(为fh:对于fh中的线路:命令,description=line.strip((.split('=',1(commands[command.rstrip((]=description.strip((print(json.dumps(commands,indent=2,sort_keys=True(

首先,不要发布屏幕截图,使用编辑器键入文本。

你必须根据你的需求进行编辑,它会根据你的样本做出一些假设。

sample_input.txt

## SASADA
# RANDOM
XXXX
[server]
server_id = 1
port = 8000
[client]
port = 8001

代码.py

all_lines = open('sample_input.txt', 'r').readlines() # reads all the lines from the text file
# skip lines, look for patterns here []
final_dict = {}
server = 0 # not yet found server
for line in all_lines:
if '[server]' in line:
final_dict['server'] = {}
server = 1
if '[client]' in line:
final_dict['client'] = {}
server = 2
if server == 1:
try:
clean_line = line.strip() # get rid of empty space
k = clean_line.split('=')[0] # get the key
v = clean_line.split('=')[1]
final_dict['server'][k] = v
except:
passs
if server == 2:
# add try except too
clean_line = line.strip() # get rid of empty space
k = clean_line.split('=')[0] # get the key
v = clean_line.split('=')[1]
final_dict['client'][k] = v

您可以通过以下方式读取file_handle中的所有行。

def read_lines(file_path, from_index, to_index):
with open(file_path, 'r') as file_handle:
return file_handle.readlines()[from_index:to_index]

下一部分是将所选行处理为json

最新更新