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

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

python代码示例如下:#!/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[0]] = sub_member[1].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--

原文:http://dgd2010.blog.51cto.com/1539422/1811598

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值