Linux under many configuration files in addition to the INI format can be used in Python configparser module, you can write a simple code of their own only "key=value" such a conf configuration file to parse into a dictionary, The key corresponding to key can be easily obtained by using the dictionary keys. The Python implementation method is relatively simple, as long as the configuration file is read row by line, each key value pair is written to the dictionary.
The Python code example is as follows:
#!/usr/bin/python# encoding: utf-8# -*- coding: utf8 -*-import refrom Copy import deepcopytry: linux_type_dict = dict () with open ('/etc/os-release ', ' r ') as f: linux_type_list = f.read (). Strip (). Split (' \ n ') except ioerror: passelse: if linux_type_list is not none: linux_type_list_to_purge = deepcopy (linux_type_list) # linux_type_list_to_purge = linux_type_list[:] # Another implement, sames to deepcopy for member in linux_type_list_to_purge: if re.seaRCH (' ^#+.* ', member) is not None: member_to_purge = member linux_type_list.remove (Member_to_purge) for member in linux_type_list: sub_member = member.split (' = ') linux_type_dict[sub_member[0]] = Sub_member[1].strip (' "') print linux_type_dict print linux_type_dict[' ID ']
For more useful bash shells or python shells, check out my github project Https://github.com/DingGuodong/LinuxBashShellScriptForOps, It contains a lot of operations-related bash scripts and Python scripts, and this project will be continuously updated!
Tag:python Parse Linux config file,python parsing configuration file, Python list to Dict
--end--
This article is from "Communication, My Favorites" blog, please make sure to keep this source http://dgd2010.blog.51cto.com/1539422/1811598
Use Python to parse the contents of a Linux conf configuration file into a dictionary format