使用Python操作配置文件(读取,写入,增加,删除)
配置文件可以有ini,cfg,conf等类型,但是结构基本都差不多。
主要有节(section)、键(key)或称option、键值(value)部分组成。
节 (section) 用方括号括起来,单独占一行,例如:
[section]
键(key)又名属性(property),单独占一行用等号连接键名和键值,例如:
name=value
比如:
account.cfg
;cfg配置文件
[account]
hostname = mk90
usr = root
password = 123456
[logging]
usr = root
time = 20190704 20:45
operate = none
注意,配置文件里面可以用分号;或者#表示注释。
Python2里面使用Configparser模块来操作配置文件(python3的版本是configparser),我用的是Python2,所以需要
import ConfigParser
Python对配置文件的基本操作:
读取、写入、添加、查询、删除、输出、修改等,总体来说比较简单,下面通过实例来说明。
在同一个文件夹下面新建 account.cfg 配置文件和 cfg_operate.py 文件
account.cfg
[account]
hostname = mk90
usr = root
usr2= other
password = 123456
cfg_operate.py
#! /bin/python
# --*-- coding:utf-8 --*--
import ConfigParser
import sys
import os
curpath = os.path.dirname(os.path.realpath(__file__)) #读取当前文件路径
cfgpath = os.path.join(curpath, "account.cfg") #返回将当前路径与"account.cfg"后的路径
print "cfgpath: ", cfgpath #输出account.cfg文件路径
myconfig=ConfigParser