python 读写配置文件—ConfigParse用法

一、读取配置文件(config.ini)

  • read(filename):读取文件内容
  • sections():获取所有section,返回list
  • options(section):获取该section所有options,返回list
  • items(section):获取options键值对,返回list
  • get(section,option):获取section的option值,返回string;getint,getboolean,getfloat同理
#coding:utf-8
import ConfigParser
config = ConfigParser.ConfigParser()
config.read("1.ini")
print config.sections()
print config.options("db")
print config.items("db")
print config.get("db", "dbuser")
print config.getint("db", "dbport")
for sections in config.sections():
    for items in config.items(sections):
        #打印单独键值对
        print items
['db', 'emain']
['dbuser', 'dbpassword', 'dbport']
[('dbuser', 'test'), ('dbpassword', 'test'), ('dbport', '3308')]
test
3308
('dbuser', 'test')
('dbpassword', 'test')
('dbport', '3308')
('emailto', '***qq.com')

 注意:在读取的时候传入的sections,options要实际存在,否则会报错。

 二、写入配置文件(config.ini)

  • write(filename):将config对象写入ini格式的文件
  • add_section(section):添加新的section
  • set(section,option,value):给section中option赋值(新增,或者是修改)
  • remove_setcion(section):删除某section
  • remove_option(section,option):删除该section下的option

配置文件内容如下:

[db]
dbuser = test
dbpassword = test
dbport = 3308

[emain]
emailto = ***qq.com
#coding:utf-8
import ConfigParser
config = ConfigParser.ConfigParser()
config.read("1.ini")
config.add_section("user")
config.set("user", "name", "Edward")
if "db" not in config.sections():
    config.add_section("db")
config.set("db","dbuser","platform")
with open("1.ini","w+") as f:
    config.write(f)

运行之后配置文件:open函数知识点传送门——https://blog.csdn.net/weixin_43533825/article/details/87524543

在对section操作之前,要先判断section是否存在,否则会报错

[db]
dbuser = platform
dbpassword = test
dbport = 3308

[emain]
emailto = ***qq.com

[user]
name = Edward

如果config对象,没有进行read("1.ini")的情况:

[db]
dbuser = platform
dbpassword = test
dbport = 3308

[emain]
emailto = ***qq.com
#coding:utf-8
import ConfigParser
config = ConfigParser.ConfigParser()
config.add_section("user")
config.set("user", "name", "Edward")
if "db" not in config.sections():#这里sections是空
    config.add_section("db")
config.set("db","dbuser","platform")
with open("1.ini","w+") as f:
    config.write(f)
[user]
name = Edward

[db]
dbuser = platform

注意:操作section之前需要判断section是否存在,避免运行抛异常~

你可能感兴趣的:(Python,基础)