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

2024-05-20 03:48:33 发布

您现在位置:Python中文网/ 问答频道 /正文

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

捕获特定块:

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

[client]
port                                = 3016

block content

生成的json是:

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

   },
   "client": {
          "port": "3016"
   }
}

resulting json

是否有任何内置功能来实现这一点

我尝试使用以下方法来解析文本文件。但它没有起作用

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))

Tags: txtclientidjsonforserverportline
2条回答

您可以通过以下方式读取文件句柄中的所有行

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

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

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

示例_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

相关问题 更多 >