lkjhgd 发表于 2016-7-7 09:19:50

利用Python将Linux conf配置文件的内容解析成字典格式

Linux下许多配置文件除了ini格式的可以用python的ConfigParser模块外,可以自己编写一段简单的代码将只有“key=value”这样的conf配置文件解析成字典,利用字典的key可以轻松获取key对应的value。python实现起来方法比较简单,只要逐行读取配置文件,将每一个键值对写入字典即可。
python代码示例如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#!/usr/bin/python
# encoding: utf-8
# -*- coding: utf8 -*-
import re
from copy import deepcopy

try:
    linux_type_dict = dict()
    with open('/etc/os-release', 'r') as f:
      linux_type_list = f.read().strip().split('\n')
except IOError:
    pass
else:
    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.strip('"')
      print linux_type_dict
      print linux_type_dict['ID']




获取更多实用的bash shell或python shell,请查阅我的github项目https://github.com/DingGuodong/LinuxBashShellScriptForOps,里面包含了很多与运维相关的bash脚本和python脚本,此项目将持续更新!
tag:python parse linux config file,python解析配置文件,python list to dict
--end--

页: [1]
查看完整版本: 利用Python将Linux conf配置文件的内容解析成字典格式