Python ConfigParser模块读写配置文件

在代码过程中,为了提高代码的可读性和降低维护成本,将一些通用信息写入配置文件,将重复使用的方法写成公共模块进行封装,使用时候直接调用即可。

这篇博客,介绍下python中利用configparser模块读写配置文件的方法,仅供参考。。

一、写入文件

示例代码如下:

# coding: utf-8
import os
import ConfigParser

PATH = "/opt/work/web/test/data"

conf = os.path.join(PATH, "conf.ini")
config = ConfigParser.ConfigParser()

# add section 添加section项
# set(section,option,value) 给section项中写入键值对
config.add_section("test")
config.set("test", "name", "shang")

with open(conf, "w+") as f:
     config.write(f)

 注:

  cf.write(filename):将configparser对象写入.ini类型的文件
  add_section():添加一个新的section
  add_set(section,option,value):对section中的option信息进行写入

二、读取文件

configparser模块支持读取.conf和.ini等类型的文件,代码如下:

# coding: utf-8
import os
import ConfigParser

PATH = "/opt/work/web/test/data"

conf = os.path.join(PATH, "conf.ini")
config = ConfigParser.ConfigParser()

# read(filename) 读文件内容
filename = config.read(conf)
print filename

# sections() 得到所有的section,以列表形式返回
sec = config.sections()
print sec

# options(section) 得到section下的所有option
opt = config.options("test")
print opt

# items 得到section的所有键值对
value = config.items("test")
print value

# get(section,option) 得到section中的option值,返回string/int类型的结果
mysql_host = config.get("test", "name")
mysql_password = config.getint("test", "age")
print mysql_host, mysql_password

执行脚本,结果如下:

['/opt/work/web/test/data/conf.ini']
['test']
['name', 'age']
[('name', 'shang'), ('age', '12')]
shang 12

 注:

  conf.read(filename):读取文件内容  
  conf.sections():
得到所有的section,并且以列表形式返回  
  conf.options(section):得到section下所有的option  
  conf.items(option):得到该section所有的键值对  
  conf.get(section,option):得到section中option的值,返回string类型的结果  
  conf.getint(section,option):
得到section中option的值,返回int类型的结果

三、删除

# coding: utf-8
import os
import ConfigParser

PATH = "/opt/work/web/test/data"

conf = os.path.join(PATH, "conf.ini")
config = ConfigParser.ConfigParser()

# remove_section(section)  删除某个section的数值
# remove_option(section,option) 删除某个section下的option的数值
config.read(conf)
config.remove_section("test")
# config.remove_option("test", "name")

with open(conf, "w+") as f:
     config.write(f)

 注:

  conf.read(filename):读取文件(这里需要注意的是:一定要先读取文件,再进行修改)
  conf.remove_section(section):删除文件中的某个section的数值
  conf.remove_option(section, option):删除文件中某个section下的option的数值

如上所示,就是configparser模块读写配置文件的方法,代码仅为参考,具体使用请自行实践。。。

原文地址:https://www.cnblogs.com/shangwei/p/15557705.html