如何用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 ####################################################
需要提取的特定块是:
[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))
请问Python是否有内置功能可以实现这个需求?
解决方案
当然有!Python内置的configparser模块就是专门处理这种类似INI格式的配置文件的,完全能满足你的需求,而且比自己写for循环处理要靠谱得多。
下面是实现的代码:
import configparser import json # 初始化配置解析器 config = configparser.ConfigParser() # 读取文件,过滤出我们需要的配置块内容 with open('conf.txt', 'r') as f: filtered_lines = [] in_config_block = False for line in f: stripped_line = line.strip() # 遇到[开头的行,标记进入配置块 if stripped_line.startswith('['): in_config_block = True filtered_lines.append(line) # 在配置块内时,保留有效键值对行,遇到注释/空行则退出配置块 elif in_config_block: if not stripped_line or stripped_line.startswith('#'): in_config_block = False else: filtered_lines.append(line) # 将过滤后的内容加载到配置解析器中 config.read_string(''.join(filtered_lines)) # 转换为字典后再输出JSON格式 config_dict = {section: dict(config.items(section)) for section in config.sections()} print(json.dumps(config_dict, indent=2))
代码说明:
- 过滤无关内容:先遍历文件,只保留
[server]、[client]这类section标记行,以及它们对应的键值对行,自动跳过报告内容、注释和空行。 - 解析配置:用
configparser的read_string方法加载过滤后的内容,它会自动识别section和对应的键值对,帮你处理好结构。 - 转JSON输出:把解析后的配置转成普通字典,再用
json.dumps输出格式化后的JSON,完全符合你的预期。
你之前的代码失败,主要是因为没处理section的层级结构,而且直接用split('=')会遇到没有等号的行(比如开头的报告行)直接报错,configparser则帮你规避了这些细节问题。
内容的提问来源于stack exchange,提问作者kanpai
相关产品推荐
相关产品推荐

